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)