A cron job runs every 5 minutes, but sometimes takes 8 minutes and two copies overlap, corrupting data. How do you prevent that?
BeginnerScenarioScheduling, automation and scripting
Answer
Situation read → Need a lock so only one instance runs.
What I'd do →
*/5 * * * * app flock -n /run/lock/sync.lock /usr/local/bin/sync.sh
Or inside the script:
exec 9>/run/lock/sync.lock
flock -n 9 || { echo "already running"; exit 0; }
Why → flock uses a kernel lock that is released automatically when the process dies, unlike a hand-made lock file that goes stale.
Interview tip → A systemd timer also won't start a second copy while the service is still active.
More on Scheduling, automation and scripting
A database dump must run every night at 1:30 AM. How do you schedule it with cron so it is reliable?BeginnerConvert that nightly cron job to a systemd timer. Why would you?IntermediateYou have 300 servers running the same cron job at midnight, and they hammer a shared API. How do you fix it?IntermediateA job must run on the last day of every month. Cron has no "last day" field. What do you do?IntermediateYou inherited a server and need to know every scheduled job on it. Where do you look?BeginnerA one-off data fix must run at 9 PM tonight, just once. How do you schedule it?Beginner