如果某脚本要运行30分钟,可以在Crontab里把脚本间隔设为至少一小时来避免冲突。而比较糟的情况是可能该脚本在执行周期内没有完成,接着第 二个脚本又开始运行了。如何确保只有一个脚本实例运行呢?一个好用的方法是利用lockf(FreeBSD 8.1下为lockf,CentOS 5.5下为flock),在脚本执行前先检测能否获取某个文件锁,以防止脚本运行冲突。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

>> flock

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 and exit

 -V, --version  output version information and exit



For more details see flock(1).

举个例子执行如下脚本:

每天23:30的时候执行一个脚本,但是执行前必须要获得排他文件锁,否则无法执行命令

30 23 * * * flock -xn /tmp/test.lock -c '/usr/local/php test.php'