Schedule Node.js job every five minutes

2020-02-21 05:33发布

问题:

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:

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



回答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.



回答3:

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



回答4:

You can use this package

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

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