Stop cron from running multiple instances of the same job

Cron & Task Scheduling (Cron/Systemd Timers/At)

Stop cron from running multiple instances of the same job

🧩 The Challenge

Everyone has seen that one backup script that takes longer to run than the actual cron interval, leading to a dozen processes fighting over the same disk I/O. I spent half a Saturday tracking down why my server load was permanently spiked, only to find twenty stale rsync jobs choking the CPU.

💡 The Fix

Use the flock command to make your cron job self-aware so it refuses to start if another instance is still holding the lock file. It’s the easiest way to prevent race conditions without writing a PID-checking nightmare in every single script.

flock -n /tmp/my_task.lock /usr/local/bin/backup-script.sh

⚙️ Why It Works

By using the non-blocking flag, the command attempts to acquire a file lock and exits immediately with a return code of 1 if someone else is already working. It effectively turns your script into a singleton without you having to manually check for PID files or process names.

🚀 Pro-Tip: Put the lock file in /run/lock instead of /tmp to keep your system clean after a reboot.

Linux Tips & Tricks | © ngelinux.com | 8/12/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted