2013-04-15

Linux crontab 不重覆執行, 前一次若尚在執行則跳過

國內的教學網站大部分都只提到怎麼用crontab,
只有翻到英文與簡中的教學

10 * * * *  flock -xn /tmp/test.lock -c '/home/test/test.sh'

這個範例是crontab裡面有個每個小時的10分啟動的/home/test/test.sh
啟動前會檢查/tmp/test.lock這個檔案, 並將之鎖定
執行完成程式後會將這個檔案解鎖
下一次跑起來如果發現有這個檔案並在鎖定的狀態,
就會失敗, 等到檔案解鎖並到下一次的執行時間才會再啟動


[~]$ flock -?
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 


參考: Prevent duplicate cron jobs running鳥哥的Linux私房菜

沒有留言: