Stop your cron jobs from stepping on each other

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

Stop your cron jobs from stepping on each other

🧩 The Challenge

Ever had a backup script that takes forever, but the cron scheduler kicks off a second instance before the first one finished? You end up with two processes fighting over the same files and suddenly your system load hits double digits for no reason.

💡 The Fix

Use a lock file check right inside your cron line to ensure only one instance of that script runs at a time. It’s a lifesaver for those “just in case” scripts that sometimes take longer than expected.

* * * * * flock -n /tmp/myjob.lock /usr/local/bin/my-script.sh

⚙️ Why It Works

The flock utility attempts to acquire an exclusive lock on the specified file, and the -n flag makes it exit immediately with a failure code if the lock is already held by someone else. By wrapping your command in this, you basically tell the second instance to just back off and try again next time.

🚀 Pro-Tip: Use a persistent path like /var/lock/ instead of /tmp/ if you’re worried about the system accidentally clearing your lock file on reboot.

Linux Tips & Tricks | © ngelinux.com | 11/3/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted