How do you prevent overlapping cron runs and capture output properly?
IntermediateConceptcron and systemd timers
Answer
*/5 * * * * flock -n /run/lock/sync.lock /opt/scripts/sync.sh >> /var/log/sync.log 2>&1
flock -nskips the run if the previous one still holds the lock.>> file 2>&1keeps both streams; better still, log throughlogger -t syncso output lands in syslog/journald.- Add
timeout 4mif a hung run should be killed before the next slot.
Without a lock, a job that occasionally runs longer than its interval piles up copies and can exhaust memory or corrupt data.
More on cron and systemd timers
Explain the five cron time fields with examples.BeginnerWhat is different about the environment a cron job runs in?BeginnerWhat is the difference between a user crontab, `/etc/crontab`, `/etc/cron.d/` and `/etc/cron.daily/`?IntermediateWhat is a systemd timer and how does it compare to cron?IntermediateWrite a minimal systemd service and timer that run a backup at 02:30 daily.IntermediateWhat is the difference between `OnCalendar=`, `OnBootSec=` and `OnUnitActiveSec=`?Advanced