繁体   English   中英

即使事件循环被占用,我怎么能总是用超时终止NodeJs脚本?

[英]How can I always terminate a NodeJs script with a timeout even if the event loop is occupied?

即使事件循环被其他东西占用,是否可以在NodeJS中使用setTimeout来终止进程?

例如,假设我的代码如下所示

setTimeout(async () => {
    // Some code I run to gracefully exit my process.
}, timeout);

while (true) {
    let r = 1;
}

我的超时中的回调将永远不会被命中,因为while循环将占用事件循环。 有什么方法可以说:“ N秒后执行以下代码而不管其他所有内容?”

我正在写硒测试,但由于某种原因,每隔一段时间测试就会“卡住”并且永远不会终止。 我基本上想在一段时间后总是超时我的测试,所以我们不会进入永远运行的测试位置。

谢谢!

由于JavaScript是单线程的,因此您要做的是使用fork创建一个worker,这将使其具有多线程的感觉。 这实际上只给我们两个节点实例,每个节点都有自己的事件循环。 这个fork会有你的无限循环,你可以用你的超时杀死它。

main.js

const cp = require('child_process')
const path = require('path')

// Create the child
const child = cp.fork(path.join(__dirname, './worker.js'), [])

// Kill after "x" milliseconds
setTimeout(() => {
  process.exit()
}, 5000);

// Listen for messages from the child
child.on('message', data => console.log(data))

接下来,您将设置您的工人:

worker.js

let i = 0;
while (true) {
  // Send the value of "i" to the parent
  process.send(i++);
}

孩子可以使用process.send(data)将有关自己的信息传达给父母。

父母可以使用child.on('message', ...)来监听来自孩子child.on('message', ...)


我们可以做的另一件事是杀死孩子而不是主过程,如果你需要主进程来做更多的东西。 在这种情况下,您可以在setTimeout调用child.kill()

const cp = require('child_process')
const path = require('path')

// Create the child
let child = cp.fork(path.join(__dirname, './worker.js'), [])

// Kill after "x" milliseconds
setTimeout(() => {
  child.kill()
}, 5000);

如果eventloop中没有更多事件,主进程将自动关闭,因此我们不需要调用process.exit()

暂无
暂无

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

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