Schedule Node.js job every five minutes


Question

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

1
20
11/4/2011 3:46:01 PM

Accepted Answer

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

68
11/4/2011 4:23:08 PM

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon