Use the flock command to solve the repetitive execution of Linux scheduled tasks

When doing a scheduled task, the task may not be executed due to some problems, causing the task to run repeatedly. To solve this problem, only one flock command is needed.

flock --help
flock (util-linux-ng 2.17.2)
Usage: flock [-sxun][-w #] fd#
flock [-sxon][-w #] file [-c] command...
flock [ -sxon][-w #] directory [-c] command...
-s --shared Get a shared lock #Get a shared lock
-x --exclusive Get an exclusive lock #Get an exclusive lock, which is the default
-u --unlock Remove a lock #Remove a lock, usually not needed, because the lock is automatically removed when the file is closed
-n --nonblock Fail rather than wait #If the lock is not obtained immediately, fail directly instead of
waiting- w --timeout Wait for a limited amount of time #If the lock is not obtained immediately, wait for the specified time
-o --close Close file descriptor before running command #Close the file descriptor holding the lock before executing the command
-c --command Run a single command string through the shell #Run a single command in the shell
-h --help Display this text #Display help
-V --version Display version #Display version

example:

I want to use rsync to schedule tasks for synchronization, I wrote a log cutting script logsplit.sh, and set the server to synchronize every 30 minutes. However, due to some other factors, the synchronization is not completed within 30 minutes, and the background will continue to execute this Schedule the task, and you can see that two rsync synchronizations are running at the same time. At this time, we need the flock command to solve the problem.

Originally my scheduled task:

*/30 * * * * /www/logspli.sh

Scheduled tasks after using flock:

*/30 * * * * flock -xn /tmp/demo.lock -c /www/logspli.sh

In this case, if the current scheduled task whsir.sh has not finished running, the next task will judge that demo.lock is locked and fail directly, waiting for the next judgment.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324986905&siteId=291194637