在其他语言中这个任务很简单,只需在 Python 中使用类似下面的东西:
while True:
# Program logic that will run forever
time.sleep(5) # Make the program wait for a few seconds
如果没有要处理的东西,我的程序也会想暂停执行。我不希望它因查询而使数据库过载。
背景
我正在尝试编写一个充当后台队列处理器的应用程序。它将检查数据库以查看队列中是否有任何项目需要处理,然后该程序会将数据写入磁盘上的文件。数据将由连接到同一数据库的不同系统的用户间歇性地添加到数据库中。
我不认为 forever npm 模块是一个很好的选择,因为该模块只是检查脚本是否正在运行,如果没有,它将重新启动它并报告任何标准错误或输出到文件。
我在代码中的想法
while(true){
db.dataqueue.find({processed: 0}).count((err, count) => {
if(count == 0){
//Sleep here or don't check the db again for a while
}else{
//Do the processing on the datas and make files. Another database find.count
//call should not happen until the queue is processed.
}
}
我不确定如何让它休眠,因为来自 mongojs 的回调不会影响 while 循环。我已经考虑过用一个 promise 来做这件事,并使这个异步的父函数可能起作用,但我不明白如何从这个答案中实现它:How to sleep the thread in node.js without affecting other threads?
我还考虑过用 setInterval 或 setTimeout 替换 while(true) 以使程序持久化。 This article has been helpful in understanding the event loop.
最佳答案
感谢 Paulpro,我找到了解决方案告诉我我走在正确的轨道上。首先,我切换到使用支持 promise 的 mongoist,然后我使用新的 async 和 await 语法来获得所需的结果:
const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));
getToProcessCount();
async function getToProcessCount(){
while(true){
const datacnt = await db.queue.count({processed: 0});
console.log(datacnt);
if(datacnt == 0){
console.log("Nothing to do, sleep for a while");
await snooze(2000);
console.log("I just woke up");
}
else{
console.log("Do some processing here");
}
}
}
async 函数允许此类函数暂停执行并等待 promise 返回,这在处理数据库查询并以同步格式编写时非常有用。 await 关键字将暂停执行,直到实现 promise 并且它实际返回数据,这就是为什么我能够从 mongodb 集合中获取记录计数并在下一行输出它的原因。
我的另一个要求是在没有任何数据要处理时强制程序暂停,这样它就不会不断地向数据库发送一堆查询,这就是贪睡功能所做的。重要的是要注意贪睡函数前面的等待,否则贪睡将被执行并立即运行下一行。
This video from Fun Fun Function确实帮助我理解了异步函数和等待语法。
关于node.js - 如何让 NodeJS 应用程序永远运行(不是 forever 模块),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49987868/