Let everyone learn Linux crontab

藏色散人
藏色散人forward
2021-07-10 15:39:222291browse

crontab

When using cron, we often encounter multiple processes when a command is started again because a certain command takes too long to run.
You can use flock, such as:

*/1 * * * * flock -xn /opt/app/nginx/test_repo/app/tasks/checkPaymentUrl.lock -c 'sudo -u apache php /opt/app/nginx/test_repo/app/console Payment checkPaymentUrl >> /dev/null 2>&1'

When multiple processes may perform operations on the same data, these processes need to ensure that other processes are not also operating to avoid damaging the data.

Usually, such a process will use a "lock file", that is, create a file to tell other processes that it is running. If the existence of that file is detected, it is considered that a process operating the same data is working. The problem is that if the process accidentally dies and the lock file is not cleared, the user can only clean it manually.
Parameter

-s,--shared:获取一个共享锁,在定向为某文件的FD上设置共享锁而未释放锁的时间内,其他进程试图在定向为此文件的FD上设置独占锁的请求失败,而其他进程试图在定向为此文件的FD上设置共享锁的请求会成功。
-x,-e,--exclusive:获取一个排它锁,或者称为写入锁,为默认项。
-u,--unlock:手动释放锁,一般情况不必须,当FD关闭时,系统会自动解锁,此参数用于脚本命令一部分需要异步执行,一部分可以同步执行的情况。
-n,--nb, --nonblock:非阻塞模式,当获取锁失败时,返回1而不是等待。
-w, --wait, --timeout seconds:设置阻塞超时,当超过设置的秒数时,退出阻塞模式,返回1,并继续执行后面的语句。
-o, --close:表示当执行command前关闭设置锁的FD,以使command的子进程不保持锁。
-c, --command command:在shell中执行其后的语句。

Example
crontab uses flock to prevent repeated execution

0 23 * * * (flock -xn ./test.lock -c "sh /root/test.sh") #-n 为非阻塞模式

Related recommendations: "Linux Video Tutorial"

The above is the detailed content of Let everyone learn Linux crontab. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete