简体   繁体   English

从子进程(NodeJS)调用setTimeout

[英]Calling setTimeout from child process (NodeJS)

I would like to call a function through setTimeout using a child process, which may exit before the setTimeout occurs. 我想使用子进程通过setTimeout调用函数,该子进程可能会在setTimeout发生之前退出。

1) I assume that if the child process calls the function (even if it's defined externally), the setTimeout will be cancelled if the child process exits. 1)我假设如果子进程调用了该函数(即使它是在外部定义的),则如果子进程退出,则setTimeout将被取消。 Is this correct? 这个对吗?

2) If so, would it be feasible to have the child process signal the parent process to execute the setTimeout instead, or is there a better way to achieve this? 2)如果是这样,让子进程发信号通知父进程执行setTimeout是可行的,还是有更好的方法来实现呢?

Thanks! 谢谢!

I'm not sure I fully understand, but let me provide some potentially applicable links and examples. 我不确定我是否完全理解,但请允许我提供一些可能适用的链接和示例。

Sending and receiving messages between the master and child process are possible with child.send / process.send which is part of the child_process module and cluster. 可以通过child.send / process.send在master和child进程之间发送和接收消息, child.send / process.send是child_process模块​​和集群的一部分。

For example, clearing a setTimeout when the child process sends a message to the master: 例如,在子进程向主机发送消息时清除setTimeout:

var cp = require('child_process');
var child = cp.fork(__dirname + '/sub.js');

var timer = setTimeout(function(){
  console.log('timed out'); 
}, 5000);

child.on('message', function(msg) {
  console.log(msg);
  clearTimeout(timer);
});

The child 孩子

setTimeout(function() {
  console.log('finished doing some long task');
  process.send({ status: 'done' });
}, 3000); // set this to something larger than 5000ms to see the timeout

You might also be interested in the exit and close event for a child process to do something similar. 您可能还对子进程执行类似操作的退出关闭事件感兴趣。

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

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