简体   繁体   中英

How to schedule a job by node-schedule module at any time of specific timezone

I want to schedule a job at 15:00 Copenhagen Time irrespective of where my server is running. I am using 'node-schedule' npm module.

没关系,但是您应该使用类似http://momentjs.com/timezone/docs/的lib来设置时间。

var a = moment.tz("2013-11-18 11:55", "America/Toronto");

I worked around so much for this problem and found a solution.

Copenhagen/Time zone: Central European Time Zone(UTC+01:00) UTC offset for CET(Central European Time) timezone is +1:00.

So to convert copenhagen time to UTC time, we need to subtract one hour from copenhagen time. Example: Copenhagen 15:00 = 14:00 UTC

If we want to schedule a job at 15:00 copenhagen and server is running anywhere then we can use following approach:

var copenhagenHour = 15;//You can set any hour at which you want to schedule a job
var copenHagenMinutes = 0;//You can set any minute
var date = new Date();
date.setUTCHours(copenhagenHour - 1);//-1 defines the UTC time offset for a particular timezone
date.setUTCMinutes(copenHagenMinutes);

var scheduledRoutes = schedule.scheduleJob({hour: date.getHours(), minute: date.getMinutes()}, function(){
console.log('call scheduled job');
});

The above console 'call scheduled job' will be printed at 15:00 in copenhagen and at 19:30 in India.

It worked for me.

Note: Currently I didn't consider 'Daylight Saving Time'.

node-schedule has RecurrenceRule() which you could use to specify timezone for the rule.

let schedule = require('node-schedule');
let rule = new schedule.RecurrenceRule();

// your timezone
rule.tz = 'Europe/Copenhagen';

// runs at 15:00:00
rule.second = 0;
rule.minute = 0;
rule.hour = 15;

// schedule
schedule.scheduleJob(rule, function () {
  console.log('Hello World!');
});

Timezones listed here: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM