我有一个节点脚本,我可以永远从命令行运行该脚本:forever index.js
当该脚本崩溃时,我希望永远重新启动它,但不是总是如此。我知道某些情况需要人工干预才能解决。在这些情况下,我希望能够以永远不会重新启动它的方式退出该过程。
有什么办法可以做到这一点吗?
我最初以为我可以使用 重新启动该进程process.exit(1),而不是使用 重新启动该进程process.exit(0),但显然情况并非如此。
这是另一种表达方式:
forever index.js该脚本应打印“hello”,退出,并且不重新启动
setTimeout(function () {
console.log("hello")
// YOUR CODE GOES HERE
}, 1500)
Run Code Online (Sandbox Code Playgroud)顺便说一句,那里的延迟只是围绕默认的 --minUpTime 1 秒进行解决
永远支持使用 --killSignal 选项自定义退出信号:
--killSignal Support exit signal customization (default is SIGKILL),
used for restarting script gracefully e.g. --killSignal=SIGTERM
Run Code Online (Sandbox Code Playgroud)
上面是永远指示用哪个终止信号来永远停止脚本已经开始。要根据脚本退出的方式有选择地永远停止运行脚本,您需要使用forever-monitor。
首先,当您希望永远不重新启动脚本时,您的脚本需要发送特定信号。这是我们的 script.js:
setTimeout(function () {
console.log('hello');
//process.kill(process.pid, 'SIGKILL'); // this will cause forever to restart the script.
setTimeout(function () {
process.kill(process.pid, 'SIGTERM'); // this will cause forever to stop the script.
}, 1000);
}, 2000);
Run Code Online (Sandbox Code Playgroud)
然后,我们需要一个带有forever-monitor的附加脚本(我们称之为script-monitor.js):
var forever = require('forever-monitor');
var child = new (forever.Monitor)('script.js', {
max: 10,
silent: false,
args: []
});
child.on('restart', function() {
console.error('Forever restarting script for ' + child.times + ' time');
});
child.on('exit:code', function(code) {
console.error('Forever detected script exited with code ' + code);
if (143 === code) child.stop(); // don't restart the script on SIGTERM
});
child.start();
Run Code Online (Sandbox Code Playgroud)
现在您可以通过运行以下命令来运行 script.js:node script-monitor.js
为了方便起见,这里列出了Node.js 中的信号事件。
| 归档时间: |
|
| 查看次数: |
3939 次 |
| 最近记录: |