Stop your cron jobs from clobbering each other

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

Stop your cron jobs from clobbering each other

🧩 The Challenge

You ever have a script that takes five minutes to run, but you set it to trigger every minute in cron because you forgot to check the execution time? I’ve seen enough production databases melt down because forty instances of the same backup script were fighting over the disk lock.

💡 The Fix

Use flock to wrap your command so it refuses to start if another instance is still holding the lock file. It keeps your server from spiraling into a recursive mess of resource contention.

* * * * * /usr/bin/flock -n /tmp/myjob.lock /path/to/script.sh

⚙️ Why It Works

The -n flag tells flock to fail immediately if the lock is held, which is exactly what you want for scheduled tasks that aren’t designed to run in parallel. It handles the atomicity for you so you don’t have to write your own pidfile logic in every single script.

🚀 Pro-Tip: Use a dedicated directory like /var/lock/ instead of /tmp/ to avoid getting nuked by a reaper script.

Linux Tips & Tricks | © ngelinux.com | 10/1/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted