brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: flock -n stops a cron job from overlapping with its own previous run

Cron
~/tips/tip-cron-flock-no-overlap

*/5 * * * * flock -n /run/lock/sync.lock /usr/local/bin/sync.sh

Skips a scheduled run when the previous one still holds a lock file.

A job that sometimes takes longer than its interval ends up running twice at once, and the second copy often does damage.

*/5 * * * * flock -n /run/lock/sync.lock /usr/local/bin/sync.sh

flock takes an exclusive lock on the file and runs the command while holding it. With -n it gives up at once when the lock is taken, so a slow run is simply skipped. Without -n flock waits and copies queue up behind each other, and -w 30 waits at most 30 seconds. The kernel drops the lock when the process ends, even after a crash, so no stale pid file is left behind. The lock file only has to be a path the cron user can write to.

Further reading: flock(1) manual page

Going deeper: Guide: find out why a Linux service failed, with journalctl

More Cron tips echo 'systemctl restart myapp' | at 03:00 tomorrow 55 23 28-31 * * [ "$(date -d tomorrow +\%d)" = 01 ] && /usr/local/bin/month-end.sh EDITOR=nano crontab -e 30 6 * * mon /usr/local/bin/weekly-report.sh @daily /usr/local/bin/backup.sh All Cron tips (32) All topics

Link