当crontab 里跑一个运行时间不确定的任务,如有时需要30秒完成,有时需要5分钟完成,而在定时任务里我是设定每1分钟运行一次。这样就容易引起上次任务还没跑完又开始跑了,导致一些问题。这时可以用进程锁来运行。如下面例子:

1
* * * * * /usr/bin/flock -xn /var/run/test.lock -c "/home/root/tmp/gotest/gohl >> /home/root/tmp/logs/gotest.log"

注意:-c 后面跟的命令要用双引号s

命令:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Usage:
flock [options] <file|directory> <command> [command args]
flock [options] <file|directory> -c <command>
flock [options] <file descriptor number>
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
-h, --help display this help and exit
-V, --version output version information and exit
For more details see flock(1).