Search code examples
node.jsscheduled-tasksschedulerschedulingjob-scheduling

looking for a node.js scheduler that wont start if the job is still running


I'm looking for a schedular/ cron for nodejs. But I need an important feature- if the jobs did not finish (when the time for it to start again arrived), I want it to not start/ delay the schedule. For example, I need to run a job every 5 minutes. The job started at 8:00, but finished only at 8:06. so I want the job of 8:05 to either wait until 8:06, or not to start at all, and wait for the next cycle at 8:10. Is there a package that does that? If not, what is the best way to implement this?


Solution

  • You can use the cron package. It allows you to start/stop the cronjob manually. Which means you can call these functions when your cronjob is finished.

    const CronJob = require('cron').CronJob;
    let job;
    
    // The function you are running
    const someFunction = () => {
        job.stop();
    
        doSomething(() => {
            // When you are done
            job.start();
        })
    };
    
    // Create new cronjob
    job = new CronJob({
        cronTime: '00 00 1 * * *',
        onTick: someFunction,
        start: false,
        timeZone: 'America/Los_Angeles'
    });
    
    // Auto start your cronjob
    job.start();