Skip to content

Instantly share code, notes, and snippets.

@maiha
Created April 19, 2019 05:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maiha/a1a534abc5549ea44774db1f139caf7d to your computer and use it in GitHub Desktop.
Save maiha/a1a534abc5549ea44774db1f139caf7d to your computer and use it in GitHub Desktop.

cronの多重起動防止

基本方針

pidof コマンドを使う (稼働中のプロセスIDを返す)

  • || で繋げてコマンド実行すればOK
  • /proc/$$/comm あたりと同じ動作なので、スクリプトの場合 bash が入ってしまう
  • pidof -x foo のように -x を入れるとスクリプトは対応できる

誤検出

基本、 ps foo | grep 相当なので、同名スクリプトは誤検出してしまう

  • 複数のディレクトリで別の ./run.sh を実行している場合など

crontab

15 5-21 * * * /data/gunosy-feeder/run
30 5-21 * * * /data/sodsp-feeder/run

対策a) フルパスで起動する

  • /tmp/a/run.sh とフルパスで実行して、 pidof -x /tmp/a/run.sh なら対応可能
  • しかし、cron 以外に人手で cd /tmp/a && ./run.sh とかされると無力

対策b) 別名にする

  • run みたいなのをやめて、もう別名にする。シンプルで全てが解決する。psにも優しい
  • 今後作る時はこれがよいが、既存プロジェクトには厳しい

対策c) プロセス名を明示

  • 名前を変更できない場合、スクリプトであれば起動するプロセス名を exec -a foo で明示できる

before

make once 2>&1 >> cron.log

after

pidof -x gunosy-feeder > /dev/null || exec -a gunosy-feeder make once 2>&1 >> cron.log
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment