7

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");
kamesh
  • 391
  • 2
  • 3
  • 11

2 Answers2

6

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);
Jerome WAGNER
  • 21,986
  • 8
  • 62
  • 77
6

In case you want to dynamically change the time, you can do it by using the CronTime method of cron job and then calling a.setTime(new CronTime(newCronTime)). In the example below, I have created a cron as constant a which runs every 4 seconds, then I change the time so that it runs every second. the functions a.start() and a.stop() are used to start and stop the schedulers.

const CronJob = require('cron').CronJob
const CronTime = require('cron').CronTime

const a = new CronJob('*/4 * * * * *', function() {
  run() // function called inside cron
}, null, false)

let run = () => {
  console.log('function called')
}

let scheduler = () => {
  console.log('CRON JOB STARTED WILL RUN IN EVERY 4 SECOND')
  a.start()
}

let schedulerStop = () => {
  a.stop()
  console.log('scheduler stopped')
}

let schedulerStatus = () => {
  console.log('cron status ---->>>', a.running)
}

let changeTime = (input) => {
  a.setTime(new CronTime(input))
  console.log('changed to every 1 second')
}

scheduler()
setTimeout(() => {
  schedulerStatus()
}, 1000)
setTimeout(() => {
  schedulerStop()
}, 9000)
setTimeout(() => {
  schedulerStatus()
}, 10000)
setTimeout(() => {
  changeTime('* * * * * *')
}, 11000)
setTimeout(() => {
  scheduler()
}, 12000)
setTimeout(() => {
  schedulerStop()
}, 16000)
Ivan
  • 34,531
  • 8
  • 55
  • 100
Danny Galiyara
  • 197
  • 2
  • 8