Search code examples
node.jsmomentjsmoment-timezone

Execute a function every midnight in a timezone (CST) different than server timezone (UTC)


I have a time zone (timerTimeZone): For e.g. "America/Chicago".

let timerTimeZone = "America/Chicago"

Our server local time is in UTC.

I want to execute a function every night at 12.00 AM in the time zone which is stored in the timerTimeZone variable.

Let's say the program is running at 6.00 PM UTC/1.00 PM CST. So the first execution should be after 11 hours (12.00 AM CST) and next subsequent executions every 24 hours.

I have been trying to use moment and moment-timezone but not able to find any way.


Solution

  • I would suggest using the excellent Cron module.

    This allows you to schedule tasks according to a cron expression, and also lets you specify an IANA timezone to use.

    I'm also logging here the next 5 dates the job will run, both in the specified timezone and UTC.

    const CronJob = require("cron").CronJob;
    
    // Run at midnight every night
    const cronExpression = "00 00 * * *";
    
    const timeZone = "America/Chicago";
    
    const cronJob = new CronJob(
        cronExpression,
        cronFunction,
        null,
        true,
        timeZone
    );
    
    function cronFunction() {
        console.log("cronFunction: Running....");
        /* Do whatever you wish here... */
    }
    
    // Get the next N dates the job will fire on...
    const nextDates = cronJob.nextDates(5);
    console.log(`Next times (${timeZone}) the job will run on:`, nextDates.map(d => d.tz(timeZone).format("YYYY-MM-DD HH:mm")));
    console.log("Next times (UTC) the job will run on:", nextDates.map(d => d.utc().format("YYYY-MM-DD HH:mm")));