Search code examples
node.jscronjob-schedulingcron-tasknode-schedule

NPM cronJob - dynamically set time


here is my code for scheduling a task. i have used separate routes for starting,stopping and changing the time as given below. please tell me if its correct. and also im getting an error for changing the time frequency.please help me.

const cronjob=require('cron').CronJob

var first='* * * * * *'

var task=function() {

    console.log('last'+job.lastDate()+' next '+job.nextDates(1));
  }

  var complete=function(){
      console.log('the end.........')
  }

var job = new cronjob(first,task, complete, false, 'Asia/Kolkata');

app.get('/start',(req,res)=>{

job.start()

console.log('is job running? ', job.running);

res.send('cron started')

})


app.get('/set',(req,res)=>{

    var time=req.headers.time    /* input taken from user for changing the frequency*/

    time='30 5 1-31 0-11 1-7'  /*hard-coded temporary for testing*/

    console.log(time)

    job.setTime(time)

})

/set api is throwing an error /Error: time must be an instance of CronTime./


Solution

  • we have to use instance of a cronTime i.e.

    const CronTime = require('cron').CronTime
    .
    .
    .
    var time=req.query.time
    //time='*/5 * * * * *'
    job.setTime(new CronTime(time))
    res.send('time changes')