检测特定的node.js脚本是否从bash运行

时间:2016-09-17 13:28:45

标签: node.js bash cron

读取为: 从bash检测(如果特定的node.js脚本正在运行)

我有一台服务器在某些操作和某些cron间隔上运行特定的node.js脚本。

脚本可能需要几个小时才能完成,但不应该同时运行多次。

shbash是否有办法检测特定脚本是否已在运行?

过程

简单地运行(if)pidof node不会起作用,因为可能还有其他不相关的节点脚本在运行。

pidfile进程文件

我能想到的最接近的半解决方案是touch /tmp/nodescript.lock,只有在脚本不存在时才运行。但显然/tmp并没有(总是)在服务器崩溃/重启时得到清理。

秘密选项编号3

也许还有其他一些我不知道的简单方法。也许我可以为进程提供某种静态标识符,当进程发生时它就消失了。有什么想法吗?

3 个答案:

答案 0 :(得分:6)

当您使用nodejs调用脚本时,它将显示在进程列表中,例如:

user       773 68.5  7.5 701904 77448 pts/0    Rl+  09:49   0:01 nodejs scriptname.js

因此,您只需使用简单的bash脚本检查ps是否存在:

#!/bin/bash

NAME="scriptname.js" # nodejs script's name here
RUN=`pgrep -f $NAME`

if [ "$RUN" == "" ]; then
 echo "Script is not running"
else
 echo "Script is running"
fi

根据您的需要进行调整并输入cron。

答案 1 :(得分:3)

我建议您使用强大的锁定机制,如下所示:

#!/bin/bash

exec 9>/path/to/lock/file
if ! flock -n 9  ; then
   echo "another instance of $0 is running";
   exit 1
fi

node arg1 arg2 arg3...

现在,只能一次运行一个节点脚本实例

答案 2 :(得分:3)

我遇到了同样的问题,最终得到了一个完全基于NodeJS的解决方案。

我使用了这个名为 ps-node 的强大模块。

在启动代码之前,您可以查看特定进程是否已在运行。

ps.lookup({
    command: 'node',
    arguments: 'your-script.js',
},
function(err, resultList){
    if (err) {
        throw new Error(err);
    }
    // check if the same process already running:
    if (resultList.length > 1){
        console.log('This script is already running.');
    }
    else{
        console.log('Do something!');
    }
});
相关问题