Pages

Thursday, December 4, 2014

Run cron job in Sails.js

This is based on the discussion about the topic here, so it's not exactly a "cron job" but it can be executed like one and also have access to all the nice features that Sails.js provides, including models.

Note: the version of Sails.js as of this post is 0.10.5.

Install node-schedule.

$ cd /my/sailsjs/app_root/
$ npm install node-schedule


Update /config/bootstrap.js so that it looks like the code below:

module.exports.bootstrap = function(cb) {

  // add the lines from here
  var schedule = require('node-schedule');
  Object.keys(sails.config.crontab).forEach(function(key) {
      var val = sails.config.crontab[key];
      schedule.scheduleJob(key, val);
  });
  // add the lines until here
  
  cb();
};


Create file /config/crontab.js and add the code below:

module.exports.crontab = {

  /*
   * The asterisks in the key are equivalent to the
   * schedule setting in crontab, i.e.
   * minute hour day month day-of-week year
   * so in the example below it will run every minute
   */

  '* * * * * *': function(){
      require('../crontab/mycooljob.js').run();
  }
};


Create directory /crontab, then create file /crontab/mycooljob.js and add the following code:

module.exports = {
    run : function(){
        console.log('do something very cool here');
    }
};

Run sails lift and after a minute, you should see "do something very cool here" in the console.