Dynamically update nodejs cronjob period

kamesh picture kamesh · Nov 30, 2015 · Viewed 7.2k times · Source

I need to do some task periodically in my nodejs app. If it was fixed period then it is working fine. But in my case the period should change dynamically. below is my code which was not working as I expected. here cronjob is not updating it's period when I changed the period.

var period = 1;
var CronJob = require('cron').CronJob;
new CronJob('*/' + period + ' * * * * *', function () {
    console.log("some task");
}, null, true, "Indian/Mauritius");


new CronJob('*/5 * * * * *', function () {
    period = period * 2;
    console.log("updating cronjob period");
}, null, true, "Indian/Mauritius");

Answer

Jerome WAGNER picture Jerome WAGNER · Nov 30, 2015

Here you are creating 2 CronJobs that will both run. In order to "change" the period, you have to first stop the first Cronjob and then create a new one.

For example (untested code)

var job;
var period = 1;
var CronJob = require('cron').CronJob;
function createCron(job, newPeriod) {
  if (job) {
    job.stop();
  }
  job = new CronJob('*/' + newPeriod + ' * * * * *', function () {
            console.log("some task");
        }, null, true, "Indian/Mauritius");
}
createCron(job, 1);
setTimeout(function() {
  period = period * 2;
  createCron(job, period);
}, 60000);