How to configure a cron job to run every other week on a certain day #176
-
Hello! The title gives it away, but I am looking on how to configure the cron jobs to run every other week on a certain day. const job = Cron("40 9 7-14,22-28 * 1", (job) => {}); And it gave me back: 2023-03-20T08:40:00.000Z,
2023-03-22T08:40:00.000Z,
2023-03-23T08:40:00.000Z,
2023-03-24T08:40:00.000Z,
2023-03-25T08:40:00.000Z,
2023-03-26T07:40:00.000Z,
2023-03-27T07:40:00.000Z,
2023-03-28T07:40:00.000Z,
2023-04-03T07:40:00.000Z,
2023-04-07T07:40:00.000Z But what I want is for it to trigger every second week on a Monday like so: 2023-03-20T08:40:00.000Z,
2023-04-03T08:40:00.000Z,
2023-04-17T08:40:00.000Z,
2023-05-01T08:40:00.000Z,
2023-05-15T08:40:00.000Z,
2023-05-29T07:40:00.000Z,
2023-06-12T07:40:00.000Z,
2023-06-26T07:40:00.000Z,
2023-07-10T07:40:00.000Z,
2023-07-24T07:40:00.000Z Is it possible to do this with the library? BTW other than me getting stuck on this the library is excellent! Thanks for making & maintaining it :) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
It isn't possible by using a cron expression alone, as the aspect of weeks isn't included in the pattern. So you'll have to make use of some library features 😄 Continuing on your solution where the job is executed between dates 7-14.22-28 every months, you'll have to disable By default cron uses
This should work better: const job = Cron("40 9 7-14,22-28 * 1", { legacyMode: false}, (job) => {});
console.log(job.nextRuns(10)); Another way would be to use a minimum interval between executions, which is larger than one week. Since you want it to execute 00:09:40, on mondays, the cron expression should look something like
Another option is to always run on mondays, and use an additional check inside the triggered function, to check for odd or even week numbers. const job = Cron("0 40 9 * * 1", (job) => {
// Check if week number is even or odd.. This is not trivial though
if(weekIsEven) {
dostuff();
}
}); console.log(job.nextRuns(10)); // will show every monday, but will only trigger every other |
Beta Was this translation helpful? Give feedback.
It isn't possible by using a cron expression alone, as the aspect of weeks isn't included in the pattern. So you'll have to make use of some library features 😄
Continuing on your solution where the job is executed between dates 7-14.22-28 every months, you'll have to disable
legacyMode
.By default cron uses
OR
to combine day of month with day of week, making the expression execute every mondag AND day 7-14 and 22-28.legacyMode: false
changes this behavior toAND
.This should work better:
Another way would be to use a minimum interval between executions, which is larger than one week…