37

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

KingFish
  • 8,773
  • 12
  • 53
  • 81

5 Answers5

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

alessioalex
  • 62,577
  • 16
  • 155
  • 122
  • 2
    What happens if the code I want to run every 5 minutes takes longer than 5 minutes to run? Will it be fired more than once? – otmezger Nov 06 '15 at 03:37
  • 4
    with `setInterval()` yes (if it's asynchronous, otherwise it will block everything), with `setTimeout()` and recursively calling the function again at the end (when it finishes) no. – alessioalex Nov 12 '15 at 14:12
  • What If I have "cluster" running , in that case it will executes multiple times. right? Please suggest what to do in that case. – maddy Dec 07 '15 at 14:20
  • 1
    I'm new this, how if run this code year over year ? – Tony Jun 11 '20 at 04:31
17

You can use this package

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

cron.schedule('*/5 * * * *', () => {
  console.log('running a task 5 minutes');
});
Hieu Dang
  • 343
  • 3
  • 11
2

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.

Christophe Vidal
  • 1,894
  • 1
  • 19
  • 13
2

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

John Vandivier
  • 2,158
  • 1
  • 17
  • 23
0

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