Stop your scheduled jobs from clobbering each other
Cron & Task Scheduling (Cron/Systemd Timers/At)
Stop your scheduled jobs from clobbering each other
🧩 The Challenge
Everyone has that one backup script that takes forever, but the cron schedule is set to run it every hour regardless of whether the previous instance is still chewing through data. I’ve spent way too many nights debugging load spikes because I accidentally launched five concurrent rsync jobs that brought the disk I/O to a screeching halt.
💡 The Fix
Use flock to ensure your script only ever runs one instance at a time, even if the cron trigger fires again while the first one is stuck. It’s the easiest way to prevent a feedback loop from eating your server alive.
flock -n /var/run/my_backup.lock /usr/local/bin/backup_script.sh
⚙️ Why It Works
Setting the -n flag makes the command exit immediately if it can’t grab the lock file, which prevents those nasty pile-ups of stale processes. It’s a clean way to handle concurrency without needing to hack PID files into your own code.
🚀 Pro-Tip: Stick the lock file in /run/user/$(id -u) if you are running the job as a regular user instead of root.
Linux Tips & Tricks | © ngelinux.com | 10/31/2026
