简体   繁体   English

即使我在 EventQueue 中有“非必要”的东西,我如何让 NodeJS 终止?

[英]How do I make NodeJS terminate even if I have “non-essential” things in the EventQueue?

I don't have good terms for everything, so please be patient.我对所有事情都没有很好的条件,所以请耐心等待。

In a NodeJS script, execution will complete once the event queue is cleared out.在 NodeJS 脚本中,一旦事件队列被清除,执行就会完成。 In my package, however, I want to add a non-essential long-running thing to the event queue (eg spawned process or setInterval call) and automatically trigger cleanup of that non-essential task once the script would naturally finish had I not added the long-running thing.但是,在我的 package 中,我想在事件队列中添加一个非必要的长时间运行的东西(例如生成的进程或 setInterval 调用),并在脚本自然完成后自动触发清理该非必要任务(如果我没有添加)长期存在的事情。

Since I'm producing a package, I could make the user of the package call a close() method (and make them responsible for keeping track of when everything else is done. But I'd rather automatically close so the user doesn't have to worry about it.由于我正在生产 package,我可以让 package 的用户调用close()方法(并让他们负责跟踪其他所有操作何时完成。但我宁愿自动关闭,这样用户就不会不得不担心它。

I'll use setInterval as an example, but I'd really like for this to work with a spawned subprocess.我将使用 setInterval 作为示例,但我真的希望它能够与衍生的子进程一起使用。 I'm hoping for something like this:我希望这样的事情:

function main() {
  let myinterval = setInterval_NonEssential(() => {
    console.log("Still alive");
  }, 1000);
  process.on('only-non-essential-work-remains', () => {
    clearInterval(myinterval);
  });

  // do any number of other things
  // ...
}

main();

Is there a way to tag event queue things in such a way?有没有办法以这种方式标记事件队列? Do you have a better suggestion for how to accomplish this?您对如何实现这一点有更好的建议吗?

setInterval returns a Timeout object which offers an unref method which tells node to ignore this handle regarding the question "is there still something going on". setInterval 返回一个 Timeout object ,它提供了一个 unref 方法,告诉节点忽略这个关于“还有什么事情发生”的问题的句柄。

Similar a lot other objects like net.Server or ChildProcess offer an unref method.与许多其他对象类似,例如 net.Server 或 ChildProcess 提供了 unref 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM