Stop cron jobs from stepping on each other

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

Stop cron jobs from stepping on each other

🧩 The Challenge

You have a backup script that usually takes five minutes but occasionally balloons to two hours because the database hits a snag. Suddenly, the next cron job kicks off while the first one is still churning, and now your CPU is melting and everything is locked up.

💡 The Fix

Use a simple lock file check so the second instance knows to back off and die quietly if the first one hasn’t finished yet. It’s a cheap way to keep your server from nuking itself during busy times.

flock -n /tmp/my-job.lock -c "/usr/local/bin/backup-script.sh"

⚙️ Why It Works

By using flock, the kernel handles the file descriptor locking for you, which is way more reliable than manually checking pgrep or trying to parse the process list. If the lock is already held, the -n flag makes the command exit immediately instead of waiting around.

🚀 Pro-Tip: Add a custom exit code to your script so you can monitor if your jobs are getting blocked via your logging system.

Linux Tips & Tricks | © ngelinux.com | 9/14/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted