I need a Nodejs scheduler that allows for tasks at different intervals

user379468 picture user379468 · Dec 10, 2013 · Viewed 144.9k times · Source

I am looking for a node job schedule that will allow me to schedule a number of tasks at different intervals. For instance,

  • call function A every 30 seconds
  • call function B every 60 seconds
  • call function C every 7 days

I also want to be able to start and stop the process.

So far, I have looked at:

  • later - the syntax confuses me, also apparently you cant schedule tasks beyond a month

  • agenda- seems the most promising, however I'm confused about the database functionality

  • timeplan - too simple, can't start and stop

I find the syntax of the latter confusing.

Answer

Tom picture Tom · Dec 10, 2013

I would recommend node-cron. It allows to run tasks using Cron patterns e.g.

'* * * * * *' - runs every second
'*/5 * * * * *' - runs every 5 seconds
'10,20,30 * * * * *' - run at 10th, 20th and 30th second of every minute
'0 * * * * *' - runs every minute
'0 0 * * * *' - runs every hour (at 0 minutes and 0 seconds)

But also more complex schedules e.g.

'00 30 11 * * 1-5' - Runs every weekday (Monday through Friday) at 11:30:00 AM. It does not run on Saturday or Sunday.

Sample code: running job every 10 minutes:

var cron = require('cron');
var cronJob = cron.job("0 */10 * * * *", function(){
    // perform operation e.g. GET request http.get() etc.
    console.info('cron job completed');
}); 
cronJob.start();

You can find more examples in node-cron wiki

More on cron configuration can be found on cron wiki

I've been using that library in many projects and it does the job. I hope that will help.