Crontab avoid multiple executions


Two ways of crontab avoiding multiple executions. The first way is to use the shell command flock to implement, The second way is to use ps aux | grep'pid'.

First Way

flock help

$ flock -h

Usage:
 flock [options] <file>|<directory> <command> [<argument>...]
 flock [options] <file>|<directory> -c <command>
 flock [options] <file descriptor number>

Manage file locks from shell scripts.

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
 -F, --no-fork            execute command without forking
     --verbose            increase verbosity

 -h, --help               display this help
 -V, --version            display version

For more details see flock(1).

crontab config

* * * * *  flock -xn /tmp/my_lock -c "php test.php"

Second Way

<?php
crontab_avoid_multi_exec($argv[0]);

//Do Something
sleep(20);

function crontab_avoid_multi_exec($filename) {
    //Querying and storing PID can use memcached, files, redis, and so on.
    $command = "ps aux | grep '{$filename}' | grep -v 'grep' | wc -l";
    exec($command, $count);
    if ( $count[0] > 1 ) {
        die("Crontab job can only run one!");
    }
}
?>

Attention Programing Language

When the parent process uses flock, the child process reuses the file descriptor as well.

Reference

https://www.php.net/manual/en/function.exec.php
https://www.cnblogs.com/wangxusummer/p/4933492.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值