Node.JS: setTimeout, which does not support process execution

I would like to add a one-hour timeout to this process so that it does not stay forever in the event of a deadlock. The only problem is that if I say setTimeout, the process does not have the ability to end early.

Is there a way to disable forced exit after an hour without delaying the process? Or am I stuck between using process.exit and without this timeout?

+7
source share
3 answers

I do not know when unref was added to Node, but now this is one of the possible solutions. Reusing Matt Code:

 var timeoutId = setTimeout(callback, 3600000); timeoutId.unref(); // Now, Node won't wait for this timeout to complete if it needs to exit earlier. 

Doc says:

In the case of setTimeout, when you create a separate timer that wakes up the event loop, creating too many of them can adversely affect the performance of the event loop - use it wisely.

Do not twitch with it.

+12
source

If you save the value returned by setTimeout , you can always cancel it before it starts with clearTimeout , for example:

 var timeoutId = setTimeout(callback, 3600000); // 1 hour // later, before an hour has passed clearTimeout(timeoutId); 
+5
source

Possible solution using a new function that is implemented as process.watchers() , but I don’t know if it is included in the released version. pull request is still open from this post.

But, generally speaking, you should write a custom setTimeout function that adds all timeouts to the counter, and right before the timeouts to the callback it will be deleted from the counter.

Then create a continuous interval and the interval will check and notice when all the walkers are just timeouts set by your user-defined function.

When he notices this, he (will clear all his timeouts, causing) to exit.

This, of course, is not very convenient, because

  • The concept is not proven. (I don't know what data will be returned by process.watchers() , or if it still works yet)
  • Interval is a polling method. (not nice if you want an immediate return at the same time with low CPU consumption)
+1
source

All Articles