KLôN KLôN - 1 year ago 37
Node.js Question

NodeJs : maintain a script running for a given time?

I have quickly and poorly written a Node.Js script without any kind of error handling which does the job and eventually crashes once in a while upon encountering an error. Careless but efficient.

To keep it running, I can use npm forever and have it restart forever. Fancy.

Now let's say I want it to run for 12 hours (with some module / code to restart it after a crash) and then stop completely.

Any simple way of achieving such a behavior ?

Answer Source

If you want your node.js process to stop itself after 12 hours, you can just set a timer for 12 hours from now and call process.exit().

setTimeout(function() {
}, 1000 * 60 * 60 * 12);

If you want to use a system like forever, but you both want to stop the program in 12 hours and don't want forever to restart it, then you can just run a chron job, scheduled for 12 hours from now to execute forever stop /somepath/yourscript.js.

P.S. There's no way that a system that crashes on its own every so often is "careless, but efficient". It may be quick to get going, but it's also loose and dangerous and is never the efficient way to code in the long run. I'd suggest you start removing all the technical debt you've baked into your code.

My favorite saying from running development teams for many years was the somewhat rhetorical question: "Why is there never enough time to do it right the first time, but always enough time to do it over to get it right."