博客 2011-12-04
1 * * * * flock -xn /var/run/rsync.lock -c ‘rsync -avlR /data/files/ 172.16.xxx.xxx:/data/files/’


flock (util-linux 2.13-pre7)
Usage: flock [-sxun][-w #] fd#
flock [-sxon][-w #] file [-c] command…
-s –shared Get a shared lock
-x –exclusive Get an exclusive lock
-u –unlock Remove a lock
-n –nonblock Fail rather than wait
-w –timeout Wait for a limited amount of time
-o –close Close file descriptor before running command
-c –command Run a single command string through the shell
-h –help Display this text
-V –version Display version
比如在rsync定时同步某文件夹的时候,可能担心上一次任务还没执行完,下一次就开始了。于是可以采用如下方式:

1 * * * * flock -xn /var/run/rsync.lock -c ‘rsync -avlR /data/files 172.16.xxx.xxx:/data’
对照usage,x创建一个独享锁,n是如果已存在就退出,然后一个lock文件,c是shell命令,具体内容就是rsync。

lockf的参数如下。

-k:一直等待获取文件锁。

-s:silent,不发出任何信息,即使拿不到文件锁。

-t seconds:设定timeout的时间是seconds秒,如果超过时间,则自动放弃。

以下Crontab计划任务执行前,需获取临时文件create.lock的文件锁,此项Crontab计划任务的内容如下:

*/10 * * * * (lockf -s -t 0 /tmp/create.lock /usr/bin/python /home/project/cron/create_tab.py
>> /home/project/logs/create.log 2>&1)