Schedule Node.js job every five minutes

@alessioalex has the right answer when controlling a job from the code, but others might stumble over here looking for a CLI solution. You can't beat sloth-cli.

Just run, for example, sloth 5 "npm start" to run npm start every 5 minutes.

This project has an example package.json usage.


This is how you should do if you had some async tasks to manage:

(function schedule() {
    background.asyncStuff().then(function() {
        console.log('Process finished, waiting 5 minutes');
        setTimeout(function() {
            console.log('Going to restart');
            schedule();
        }, 1000 * 60 * 5);
    }).catch(err => console.error('error in scheduler', err));
})();

You cannot guarantee however when it will start, but at least you will not run multiple time the job at the same time, if your job takes more than 5 minutes to execute.

You may still use setInterval for scheduling an async job, but if you do so, you should at least flag the processed tasks as "being processed", so that if the job is going to be scheduled a second time before the previous finishes, your logic may decide to not process the tasks which are still processed.


var minutes = 5, the_interval = minutes * 60 * 1000;
setInterval(function() {
  console.log("I am doing my 5 minutes check");
  // do your stuff here
}, the_interval);

Save that code as node_regular_job.js and run it :)


You can use this package

var cron = require('node-cron');

cron.schedule('*/5 * * * *', () => {
  console.log('running a task 5 minutes');
});