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