Use flock to lock crontab under linux

Use flock to lock crontab

When using crontab to configure the script, many redundant processes will appear when the execution time is long. Use flock to lock them, and this problem will not occur again. For
example:
if a task is set to be executed every 1 minute, but there are It may take 2 minutes to execute the task, at which time the system will execute the task again. Resulting in two identical tasks being executed. In this case, some concurrency problems may occur, which in serious cases can lead to a vicious cycle of dirty data/performance bottlenecks.
This problem can be avoided by using flock to establish an exclusive lock. If a process adds an exclusive lock to a process, other processes cannot lock it. You can choose to wait for a timeout or return immediately.Insert image description here

* * * * * flock -xn /root/yck/cl.lock -c 'sh /root/yck/cl.sh >> /root/yck/cl526.log 2>&1'
flock -s --shared: 
获得一个共享锁
flock -x --exclusive: 
获得一个独占锁/排他锁
flock -u --unlock:
移除一个锁,通常是不需要的,脚本执行完会自动丢弃锁。
flock -n --nonblock:    
如果没有立即获得锁,直接失败而不是等待
flock -w --timeout: 
如果没有立即获得锁,等待指定时间。
flock -o --close:
在运行命令前关闭文件的描述符号。用于如果命令产生子进程时会不受锁的控制。
flock -c --command: 
在shell中运行一个单独的命令

Since there is no lock, it will lead to a waste of resources and the process will be executed all the time, which will cause the script to run repeatedly.
After using flock to lock, it will not run repeatedly:
test.lock only needs to have the maximum read and write permissions chmod 777 test.lock
which involves a A little knowledge point is how to kill redundant processes:
it is more convenient to use pkill

Script explanation flock -xn /home/jingguoliang/project/sh/paysleep.lock -c
adds file lock to the following script process. The format is: flock parameter lock file address parameter '/bin/sh
/home/jingguoliang/project/sh /paybiz.sh >/dev/null 2>&1' Execution script address and print log
Note: Be sure to add quotation marks, otherwise the script will not be executed! ! !

Guess you like

Origin blog.csdn.net/weixin_45163291/article/details/130886874