Search code examples
node.jscron

Node.js: Get time till next cron job


I have a server that has a cron job running at certain times in the day. I want to get the time till the next job will execute. I looked at the cron and node-cron packages in npm, but they don't seem to have this functionality.

How can I implement this functionality by myself for these packages?


Solution

  • The cron package allows you to get the next runs of the cron job, so you can use this to determine the time until the next run.

    This is exposed in the CronJob.nextDates() function.

    const CronJob = require("cron").CronJob;
    
    const cronJob = new CronJob(
        "*/30 * * * * *",
        () => {
            console.log("Timestamp: ", new Date());
        },
        null,
        true,
        "UTC"
    );
    
    setInterval(() => { 
        let timeUntilNextRunSeconds = cronJob.nextDates(1)[0].unix() - new Date().getTime()/1000;
        console.log("Time until next run (s): ", Math.round(timeUntilNextRunSeconds));
    }, 1000);