Search code examples
javascriptnode.jstypescriptnode-schedule

Run tasks at startup in node-schedule?


When using https://github.com/node-schedule/node-schedule I would like to run the job when it's defined and periodically after that, however it does start after a certain period of time. Currently, I defined it like:

void myFunction();
scheduleJob({ rule: "*/5 * * * *" }, () => {
  void myFunction();
});

Is there any better way to do this?


Solution

  • Node schedule does not have this functionality to call function on initialisation of scheduled job.

    One way, is to do it the way you have defined it as.

    Another way is to use the cron npm package.

    const cronJob = require('cron').CronJob;
    
    const myJob = new cronJob('"*/5 * * * *"',() => {
        myFunction();
     },() => {
     },
     true
    ); 
    

    Here, the true flag signals the module implementation to run the function on initialisation of the scheduled job.