方法一:进程数量判断

crontab启动指令

*/1 * * * * if [ `ps aux| grep 'weixinmsgtask send' | grep -v grep | wc -l` -lt 1 ]; then /web/tell/protected/yiic weixinmsgtask send >> /web/tell/protected/runtime/weixinmsgtask.log 2>&1; fi

重启脚本restart.sh

#! /bin/bash

PID=`ps aux| grep "weixinmsgtask send" |grep -v 'grep weixinmsgtask send' | awk '{print $2}' | sed -n '1p'`
echo "PID: ${PID}"
if [[ $PID -gt 0 ]]; then
        echo -e "kill -9 -${PID}\n"
        kill -9 -${PID} | /web/tell/protected/yiic weixinmsgtask unlock
        echo -e "Process ended, and unlocked\n"
fi

方法二:flock 命令实现

flock 命令,是Linux 的文件锁命令。可以通过一个锁文件,来控制在shell 中逻辑的互斥性。用法如下;
 flock [options] <file|directory> <command> [command args]
 flock [options] <file|directory> -c <command>
 flock [options] <file descriptor number>

Options:
 -s  --shared             get a shared lock
 -x  --exclusive          get an exclusive lock (default)
 -u  --unlock             remove a lock
 -n  --nonblock           fail rather than wait
 -w  --timeout <secs>     wait for a limited amount of time
 -E  --conflict-exit-code <number>  exit code after conflict or timeout
 -o  --close              close file descriptor before running command
 -c  --command <command>  run a single command string through the shell

 -h, --help     display this help and exit
 -V, --version  output version information and exit

For more details see flock(1).

用它来实现我们上边说的“任务互斥”。可如下配置:

*/10 * * * * /bin/bash do_somethings_with_long_time.sh 

# new 
*/10 * * * * flock -xn /tmp/my.lock -c "/bin/bash do_somethings_with_long_time.sh "

x 表示文件锁为互斥文件锁,这个参数可以省略,默认即为互斥文件锁。
n 表示当有任务执行时,直接退出,符合我们的逾期。

除了上边的功能,大家还可以实现排队等待、共享锁等功能。可如下配置:

*/10 * * * * flock -w 20 /tmp/my.lock -c "/bin/bash do_somethings_with_long_time.sh "

# 共享锁
*/10 * * * * flock -s /tmp/my.lock -c "/bin/bash do_somethings_with_long_time.sh "

# 忽略锁,直接执行
*/10 * * * * flock -u /tmp/my.lock -c "/bin/bash do_somethings_with_long_time.sh "

# 自定义退出码
*/10 * * * * flock -E 1 -w 20 /tmp/my.lock -c "/bin/bash do_somethings_with_long_time.sh "

这里需要注意,在自定义退出码时,尽量使用1位的数字,当使用多位数字时,会出现不是自定义的其他返回码。

标签: none

添加新评论