簡體   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