Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically update nodejs cronjob period

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");
like image 871
kamesh Avatar asked Nov 30 '15 07:11

kamesh


2 Answers

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)
like image 71
Danny Galiyara Avatar answered Sep 22 '22 12:09

Danny Galiyara


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);
like image 40
Jerome WAGNER Avatar answered Sep 21 '22 12:09

Jerome WAGNER