事件循环为空或超时后退出Node.js进程 [英] Exit Node.js process after event loop is empty OR after timeout

查看:75
本文介绍了事件循环为空或超时后退出Node.js进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Node应用程序在做一些异步的事情,而且我不能抓住很多模块之一做不好的事情并被卡住的机会,因此该应用程序永远不会退出.(这只是在向服务发送日志消息时发生的.)

I have a Node app doing some asynchronous things, and I can't take the chance that one of the many modules does something bad and gets stuck, so the app will never exit. (It just happened when sending log messages to a service.)

我不能直接使用 process.exit ,因为无论有多少异步操作待处理,它都会终止.还是我想尽早退出,所以不会这样做:

I can't use process.exit directly, because it will terminate no matter how many asynchronous operations are pending. Still I'd like to exit as early as possible, so this won't do:

function exit() {
    setTimeout(function() {
        process.exit(1);
    }, 10000);
}

因为这将等待10秒钟,即使一切正常,并且所有异步事件在1秒钟后完成.

Because that will wait 10 seconds, even if everything went ok and all async events finished after 1 second.

我正在考虑检查事件循环(除了此计时器之外)是否为空,然后退出.可以通过某些未公开文档的处理方法来完成,但是我更喜欢避免使用诸如此类的可疑内容.关于解决此问题的更好方法的任何想法吗?

I'm considering checking if the event loop is empty except for this timer, then exit. That could possibly be done through some undocumented process methods, but I prefer avoiding shady stuff like that. Any ideas about a better way to solve this?

推荐答案

您可以将计时器设置为停留"异步操作的超时时间.

You can set your timer to whatever you want the timeout duration to be for a "stuck" async operation.

然后 .unref()计时器.这样可以防止计时器本身退出node.js,因此在完成所有异步操作或计时器触发时(以先到者为准),计时器将退出.

Then .unref() the timer. That will keep the timer itself from keeping node.js from exiting so it will exit when all the async operations are done or the timer fires, whichever comes first.

function exit() {
    var t = setTimeout(function() {
        process.exit(1);
    }, 10000);
    // allow process to exist naturally before the timer if it is ready to
    t.unref();
}

某事告诉我,一个更具可控性和健壮性的解决方案将是针对每个单独的异步事件进行更健壮的编码.诸如外部服务器的HTTP请求之类的可能卡住的事情都有自己的超时设置,因此,如果进行设置,它们将以一种或另一种方式自行完成,并且不会冒外部设备冒风险的风险.甚至在卡住但很慢的情况下,异步操作完成之前,计时器可能就会触发.

Something tells me that a more controllable and robust solution would be to code more robustly on each individual async event. The kinds of things that can get stuck like an HTTP request of an external server have their own timeout settings so if you set them, then they will complete one way or the other on their own and you don't run the risk that your external timer might fire before the async operation completes when it wasn't even stuck, but just slow.

这篇关于事件循环为空或超时后退出Node.js进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆