How does setTimeout work in Node.JS?

后端 未结 5 1015
心在旅途
心在旅途 2020-11-30 19:35

I guess that once it\'s executed it\'s on the queue, but in the queue is there any assurance it will invoke exactly after X milliseconds? Or will other heavy tasks higher on

5条回答
  •  悲&欢浪女
    2020-11-30 20:26

    The only way to ensure code is executed is to place your setTimeout logic in a different process.

    Use the child process module to spawn a new node.js program that does your logic and pass data to that process through some kind of a stream (maybe tcp).

    This way even if some long blocking code is running in your main process your child process has already started itself and placed a setTimeout in a new process and a new thread and will thus run when you expect it to.

    Further complication are at a hardware level where you have more threads running then processes and thus context switching will cause (very minor) delays from your expected timing. This should be neglible and if it matters you need to seriously consider what your trying to do, why you need such accuracy and what kind of real time alternative hardware is available to do the job instead.

    In general using child processes and running multiple node applications as separate processes together with a load balancer or shared data storage (like redis) is important for scaling your code.

提交回复
热议问题