简体   繁体   English

在Node.js中,setTimeout是否可靠?

[英]In Node.js, is setTimeout reliable?

I need to perform many "setTimeouts" 60 seconds. 我需要执行许多“ setTimeouts” 60秒。 Basically, I'm creating a database record, and 60 seconds from now, I need to check whether the database record was changed. 基本上,我正在创建数据库记录,从现在开始60秒钟,我需要检查数据库记录是否已更改。

I don't want to implement a "job queue" since it's such a simple thing, and I definitely need to check it around the 60 second mark. 我不想实现“作业队列”,因为它很简单,因此我绝对需要在60秒左右检查一下。

Is it reliable, or will it cause issues? 它是可靠的,还是会引起问题?

When you use setTimeout or setInterval the only guarantee that you get is that the code will not be executed before the programmed time. 当使用setTimeoutsetInterval ,唯一得到的保证是不会在编程的时间之前执行代码。

It can however start somewhat later because other code that is being executed when the clock ticks (in other words other code will not be interrupted in the middle of the handling of an event to process a timeout or interval event). 但是,它可以稍后开始,因为在时钟滴答时正在执行的其他代码(换句话说,其他代码不会在处理超时或间隔事件的事件处理过程中被中断)。

If you don't have long blocking processing in your code it means that timed events will be reasonably accurate. 如果您的代码中没有长时间的阻塞处理,则意味着定时事件将相当准确。 If you are instead using long blocking calls then probably node is not the correct tool (it's designed around the idea of avoiding blocking "synch" calls). 如果您使用的是长时阻塞调用,则node可能不是正确的工具(它是围绕避免阻塞“ synch”调用而设计的)。

you should try WorkerTimer.js it is more good for handling background processes and more accurate than the traditional setInterval or Timeout. 您应该尝试使用WorkerTimer.js,它比传统的setInterval或Timeout更适合处理后台进程,并且更准确。

it is available as a node.js npm package. 它可以作为node.js npm软件包使用。 https://www.npmjs.com/package/worker-timer https://www.npmjs.com/package/worker-timer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM