How to create a cronjob in Sails

cronjob node js

Create a cronjob with Sails js, sails-hook-schedule not working

 

Recently i started a project in Sails JS, what is a mvc Framework for node JS.  This framework is  quit new for me, but after some frustation and trial and error i start to like this framework.

For example, i  wanted to create a simple cronjob in Sails, but the latest module from sails doesn’t work (https://www.npmjs.com/package/sails-hook-schedule).

I am using sails 0.12.3 btw..

So this is what i did.

 

Install node-schedule

Open your command line and type this npm –save install node-schedule

Create a crontab folder in the root

Like this

crontab sails js

Add your cronjobs into the crontab folder

So create crontab/mytest.js in the crontab folder and paste your business logic in it like this:

// JS CODE
module.exports = {
run : function(){
console.log('business logic running every minute');
}
};

SyntaxHighLighter © by Melibu

Create a crontab file in config/crontab.js

Paste this code in the crontab.js. What i am doing here is creating a method where i require my cronjob, finally i append the method to the jsonArray, so the config/bootstrap.js will execute the file.

// JS CODE
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
*/
crons:function()
{
var jsonArray = [];
jsonArray.push({interval:'*/1 * * * * * ',method:'mytest'});
// add more cronjobs if you want like below
// but dont forget to add a new method.
//jsonArray.push({interval:'*/1 * * * * * ',method:'anothertest'});
return jsonArray;
},
// declare the method mytest
// and add it in the crons function
mytest: function(){
require('../crontab/mytest.js').run();
}
/*
anothertest:function(){
require('../crontab/anothertest.js').run();
}
*/
};

SyntaxHighLighter © by Melibu

 Open your config/bootstrap.js and add this code

// JS CODE
module.exports.bootstrap = function(cb) {
_.extend(sails.hooks.http.app.locals, sails.config.http.locals);
// add the lines from here
// bootstrapping all the cronjobs in the crontab folder
var schedule = require('node-schedule');
sails.config.crontab.crons().forEach(function(item){
schedule.scheduleJob(item.interval,sails.config.crontab[item.method]);
});
// It's very important to trigger this callback method when you are finished
// with the bootstrap! (otherwise your server will never lift, since it's waiting on the bootstrap)
cb();
};

SyntaxHighLighter © by Melibu

 

 Finally run sails l and you should see a message running every minute.

 

Thats it and good luck :):)

 

Deel dit artikel met je vriendenShare on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someonePin on Pinterest
1 Comment  

  • Jan Willem

    Thanks for the tut, seems to work for me 🙂

    juli 27, 2016 - 8:09 pm/ Reply

Leave a Reply