node-cron timezone working only when time-zone is same as machines time zone

15.6k Views Asked by At

EDIT: - this has been resolved in "node-cron" version > "3.0"

I have the following code. "node-cron": "^2.0.3"

cron.schedule('46 00 * * *',() => {
   //code to be executed
  console.log("Tik")
  },{
    scheduled: true,
    timezone: "America/New_York"
  });

As per my understanding, this should fire at 12:46 am America/New_York time irrespective of my machine timezone. But it doesn't work till I match the timezone with hosting machine time e.g if my machine time zone is Europe/London and I use timezone: "Europe/London" the cron will work at the exact time.

I want to schedule cron for the specific timezone. Since I am dealing with few timezones so running cron every half hour and doing checks dosent look effecient.

1

There are 1 best solutions below

8
On BEST ANSWER

Ok, so I am slightly shocked at the reasons behind this error. node-cron uses tz-offset to calculate timezone offsets... but this module does not account for Daylight Saving Time! So I believe this library is fundamentally flawed, since a lot of timezones use DST (including, of course America/New_York. Issues have been raised for this: https://github.com/node-cron/tz-offset/issues/8.

This means your cron job will be run at 01:46, or exactly one hour late. Now it will run at the right time for about half the year, this almost makes this issue worse.

I would suggest trying the cron module, the code will be very similar, but will deal with timezones properly, since it uses luxon to calculate UTC offsets.

const CronJob = require('cron').CronJob;
const job = new CronJob('46 00 * * *', () => {
    console.log('Tik');
}, null, true, 'America/New_York');
job.start();

Update: This looks likes it is now fixed in node-cron.