Stop letting your cron jobs stomp all over each other

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

Stop letting your cron jobs stomp all over each other

🧩 The Challenge

Everyone has that one backup script that runs every hour, but then it hits a massive directory and starts hogging resources long after the next hour has rolled around. Watching two instances of the same script fighting over the same files is a quick way to watch your disk I/O go through the roof.

💡 The Fix

Use a simple lockfile check at the start of your script to make sure only one instance is ever active at any given time. It is a tiny bit of code that saves you from a massive headache later.

(flock -n /tmp/my_script.lock -c "/path/to/my_script.sh") || exit 1

⚙️ Why It Works

The flock command attempts to acquire an exclusive lock on a file descriptor, and the -n flag tells it to exit immediately if someone else already holds that lock. You stop the script dead in its tracks before the secondary process can even spawn its sub-processes.

🚀 Pro-Tip: Always keep your lock files in /tmp or /var/run so they disappear if the system reboots.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted