每五分钟安排一次 Node.js 作业
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8011962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Schedule Node.js job every five minutes
提问by Paul
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.
我是 node.js 的新手。我需要 node.js 每五分钟查询一个 mongodb,获取特定数据,然后使用 socket.io,允许订阅的 Web 客户端访问这些数据。我已经设置了 socket.io 部分,当然还有 mongo,我只需要知道如何让 node.js 每五分钟运行一次,然后发布到 socket.io。
What's the best solution for this?
什么是最好的解决方案?
Thanks
谢谢
回答by alessioalex
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 :)
将该代码保存为 node_regular_job.js 并运行它:)
回答by Hiu D
You can use this package
你可以使用这个包
var cron = require('node-cron');
cron.schedule('*/5 * * * *', () => {
console.log('running a task 5 minutes');
});
回答by Christophe Vidal
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.
但是,您无法保证它何时开始,但至少您不会同时多次运行该作业,如果您的作业执行时间超过 5 分钟。
You may still use setIntervalfor 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.
您可能仍然使用setInterval调度异步作业,但如果您这样做,您至少应该将已处理的任务标记为“正在处理”,以便如果要在上一次完成之前第二次调度作业,您的逻辑可以决定不处理仍在处理的任务。
回答by John Vandivier
@alessioalex has the right answerwhen controlling a job from the code, but others might stumble over here looking for a CLI solution. You can't beat sloth-cli.
@alessioalex 在从代码控制作业时有正确的答案,但其他人可能会在这里绊倒寻找 CLI 解决方案。你打不过sloth-cli。
Just run, for example, sloth 5 "npm start"to run npm startevery 5 minutes.
只需运行,例如,每 5 分钟sloth 5 "npm start"运行npm start一次。
This projecthas an example package.jsonusage.
这个项目有一个示例package.json用法。

