javascriptnode.jscronnode-modulesnode-cron

Get next cron job timing in node-cron


In node-cron, how do I get the timing of the next cron-job? e.g. cronJob.nextCronJob().time, or other properties. There are no methods in the documentation to show this.


Solution

  • I'm not aware of any way of getting this using the node-cron module. You can do this with the cron module however, using the cronJob.nextDates() function, like so:

    const CronJob = require("cron").CronJob;
    
    const cronJob = new CronJob(
        "*/30 * * * * *",
        () => {
            console.log("Timestamp: ", new Date());
        },
        null,
        true
    );
    
    setInterval(() => { 
        console.log("Next job time:", cronJob.nextDates().toISOString());
    }, 5000);
    

    If you have to use the node-cron module, you could have a look at cron-parser, this will parse a cron expression and give you the next run time(s), e.g.

    const parser = require('cron-parser');
    
    const cronExpression = "*/30 * * * * *";
    const interval = parser.parseExpression(cronExpression);
    console.log('Next run:', interval.next().toISOString());