Roman Nozhenko
Roman Nozhenko

Reputation: 628

cron operation on specific days of the month

I would like to clarify if I made the correct date for the CRON task? Stack: Next.js/express.js

His task, after 7 days (week), in the first minute of these date numbers: 8, 15, 22, 29 => to complete the task, except February (for obvious reasons).

cron version => "^1.7.0"

my variant:

import { CronJob } from 'cron';

export const myJob = new CronJob('0 0 8,15,22,29 1,3,4,5,6,7,8,9,10,11,12 * *', async () => {
    const instanceId = process.env['INSTANCE_ID'];
    if (parseInt(instanceId, 10) === 0) {
        ...
    }
});

And additionally, maybe there is a way to exclude February, rather than write the entire list without it?

Very thanks!

Upvotes: 1

Views: 950

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30685

I think you can simplify your Cron expression to 0 0 8,15,22,29 * *, as long as you want it to run on February 8th,15th and 22nd. (and 29th each leap year (which I assume you do!))

If you wish to skip February completely, you could use 0 0 8,15,22,29 1,3-12 *. I find Crontab.guru very useful for parsing these expressions: https://crontab.guru/#0_0_8,15,22,29_1,3-12_*

In any case you can print out the next, say, 50 times the job will run using the very handy nextDates() function (here: cron api).

const myJob = new CronJob('0 0 8,15,22,29 * *', async () => {
    console.log("Cron job running!");
});

// Print the next 50 dates to the console.
console.log(myJob.nextDates(50).map(m => m.format("YYYY-MM-DD HH:mm")));

This will look something like:

[
  '2021-05-29 00:00', '2021-06-08 00:00', '2021-06-15 00:00',
  '2021-06-22 00:00', '2021-06-29 00:00', '2021-07-08 00:00',
  '2021-07-15 00:00', '2021-07-22 00:00', '2021-07-29 00:00',
  '2021-08-08 00:00', '2021-08-15 00:00', '2021-08-22 00:00',
  '2021-08-29 00:00', '2021-09-08 00:00', '2021-09-15 00:00',
  '2021-09-22 00:00', '2021-09-29 00:00', '2021-10-08 00:00',
  '2021-10-15 00:00', '2021-10-22 00:00', '2021-10-29 00:00',
  '2021-11-08 00:00', '2021-11-15 00:00', '2021-11-22 00:00',
  '2021-11-29 00:00', '2021-12-08 00:00', '2021-12-15 00:00',
  '2021-12-22 00:00', '2021-12-29 00:00', '2022-01-08 00:00',
  '2022-01-15 00:00', '2022-01-22 00:00', '2022-01-29 00:00',
  '2022-02-08 00:00', '2022-02-15 00:00', '2022-02-22 00:00',
  '2022-03-08 00:00', '2022-03-15 00:00', '2022-03-22 00:00',
  '2022-03-29 00:00', '2022-04-08 00:00', '2022-04-15 00:00',
  '2022-04-22 00:00', '2022-04-29 00:00', '2022-05-08 00:00',
  '2022-05-15 00:00', '2022-05-22 00:00', '2022-05-29 00:00',
  '2022-06-08 00:00', '2022-06-15 00:00'
]

Upvotes: 1

Related Questions