KingFish
KingFish

Reputation: 9173

Schedule Node.js job every five minutes

I'm new to node.js. I need node.js to query a mongodb every five mins, get specific data, then using socket.io, allow subscribed web clients to access this data. I already have the socket.io part set up and of course mongo, I just need to know how to have node.js run every five minutes then post to socket.io.

What's the best solution for this?

Thanks

Upvotes: 37

Views: 70213

Answers (5)

Mahdi Movassagh
Mahdi Movassagh

Reputation: 19

there are lots of Schedule package that would help you to do this in node.js . Just choose one of them based on your needs

following are list of packages: Agenda, Node-schedule, Node-cron, Bree, Cron, Bull

Upvotes: 1

Hieu Dang
Hieu Dang

Reputation: 403

You can use this package

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

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

Upvotes: 21

John Vandivier
John Vandivier

Reputation: 2426

@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.

Upvotes: 3

Christophe Vidal
Christophe Vidal

Reputation: 1942

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.

Upvotes: 3

alessioalex
alessioalex

Reputation: 63683

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 :)

Upvotes: 99

Related Questions