Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.JS: setTimeout that does not keep the process running

I would like to add a one hour timeout to this process so that it will not stay forever in the case of a stream deadlock. The only problem is if I say setTimeout, the process has no opportunity to end ahead of schedule.

Is there a way to put in a forced exit timeout after about an hour, without keeping the process running? Or am I stuck between using process.exit and doing without this timeout?

like image 847
700 Software Avatar asked May 07 '11 21:05

700 Software


2 Answers

I don't know when unref was added to Node but this is now one possible solution. Reusing Matt's code:

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

The doc says:

In the case of setTimeout when you unref you create a separate timer that will wakeup the event loop, creating too many of these may adversely effect event loop performance -- use wisely.

Don't go hog wild with it.

like image 166
Louis Avatar answered Oct 26 '22 13:10

Louis


If you save the value returned by setTimeout you can always cancel it before it fires with clearTimeout, like this:

var timeoutId = setTimeout(callback, 3600000); // 1 hour

// later, before an hour has passed
clearTimeout(timeoutId);
like image 26
Matt Ball Avatar answered Oct 26 '22 13:10

Matt Ball