Cron & Task Scheduling (Cron/Systemd Timers/At)
Stop cron jobs from stepping on each other
🧩 The Challenge
We have all had those messy backup scripts that decide to run again while the previous run is still chewing through gigabytes of data. Eventually, the server load spikes high enough to make the machine look like a space heater, and everything just grinds to a halt.
💡 The Fix
Use the flock command to wrap your cron task, which acts as a file-level lock. It’s the easiest way to ensure only one instance of your script is ever active at once.
flock -n /tmp/my_script.lock /usr/local/bin/my_script.sh
⚙️ Why It Works
Adding the -n flag tells the system to exit immediately if the lock is held by another process instead of queuing up and waiting. It’s a clean way to keep your concurrency sane without needing to write PID-checking logic into your actual scripts.
🚀 Pro-Tip: Use a dedicated lock directory under /run/lock/ instead of /tmp for better security and persistence.
Linux Tips & Tricks | © ngelinux.com | 9/9/2026
