Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cronjobs in node.js

Tags:

Is there a possibility to periodically call functions at a specific time of the day in node.js? My first implementation was

setInterval(functionName(),(24*60*60*1000)); 

This is suboptimal, because it will restart every time I restart node. Are there better possibilities to implement this?

like image 308
Thomas Avatar asked Apr 12 '11 13:04

Thomas


People also ask

What is a cron job in node JS?

The node-cron module is tiny task scheduler in pure JavaScript for node. js based on GNU crontab. This module allows you to schedule task in node. js using full crontab syntax.

What is * * * * * In cron job?

What does * mean in Cron? The asterisk * is used as a wildcard in Cron. * sets the execution of a task to any minute, hour, day, weekday, or month.


2 Answers

To guard against restarts you need to create a persistent data stored job.

Something like :

Job = {     _id: Number,     job: String,     dueDate: Date,     completed: Boolean } 

Then have some code as follows:

var createJob = function(url, date) {     var j = db.create(Job, function(j) {          j.job = url;          j.dueDate = date;          j.save();     }); };  var runJob = function(j) {     var id = j._id;     setInterval(j.dueDate - Date.now(), function() {          db.getOne(Job, { _id : id }, function(j) {              require(j.job);              j.finished = true;              j.save();            });     });     j = null; }; 

On start up you just have to do something like :

db.get(Job, { finished: false }, function(jobs) {     jobs.forEach(runJob); }); 

Replace the generic db with MongoDB, CouchDB, Redis, etc.

like image 67
Raynos Avatar answered Sep 20 '22 18:09

Raynos


It's an old question, but in addition to the accepted answer a library with examples is worth mentioning.

cron is a lightweight package which runs the specified function at given interval, using only system's time and no db persistence.

const CronJob = require('cron').CronJob; const jobFiveMinutes = require("./job.five-minutes"); const jobMondayMorning = require("./job.monday-morning");  var jobs = [     new CronJob({         cronTime: "00 */5 * * * *", //every five minutes         onTick: function() {             jobFiveMinutes();         },         start: false, //don't start immediately         timeZone: 'America/Los_Angeles'     }),     new CronJob({         cronTime: "00 00 9 * * 1", //9 am Monday morning         onTick: function() {             jobMondayMorning();         },         start: false,         timeZone: 'America/Los_Angeles'     }), ];  jobs.forEach(function(job) {     job.start(); //start the jobs }); 

Above, we required two files and call them inside of two cronjobs, set at different intervals. The files simply export the functions:

//job.five-minutes.js module.exports = function(){     console.log("runs every five minutes") };  //job.monday-morning.js module.exports = function(){     console.log("runs every monday morning at 9 am, Los Angeles time") }; 

Whether you run it locally or on remote server in any region, it will run according to the passed timezone (which is optional though, and does not matter in case of minutes).

Also, restarting the server/script will have no affect on its working as it's synced with system time. A "00 */5 * * * *" job will run on each multiple of 5 i.e. 5, 10, 15, 20 and so on. So, even if you restart the script at 24, it will run at 25 not 29.

Lastly, the package has extended the cron syntax to include seconds on the left most. Therefore, you can even tell at what exact second of the minute you want to run the job.

like image 24
Talha Awan Avatar answered Sep 20 '22 18:09

Talha Awan