Cron & Task Scheduling (Cron/Systemd Timers/At)
Stop cron jobs from nuking your server’s CPU with overlapping runs
🧩 The Challenge
Everyone has that one backup script that takes ten minutes to run, but occasionally it hangs and then the next cron job kicks off while the first one is still churning. Suddenly you have five copies of the same process eating your CPU and locking your files, and you’re left wondering why the load average is hitting 40.
💡 The Fix
Use a lockfile to make sure only one instance of the script runs at any given time. If the script sees that the lockfile already exists, it just bails out gracefully instead of creating a massive headache.
(
flock -n /tmp/my_script.lock /usr/local/bin/my_heavy_script.sh
) || echo "Script is already running, skipping this round."
⚙️ Why It Works
The flock command checks for the file descriptor and exits immediately if it can’t grab the lock, which keeps your resource usage sane. It is a hell of a lot cleaner than writing complex PID-checking logic in your bash scripts.
🚀 Pro-Tip: Use the -n flag for non-blocking mode if you want to skip the job entirely instead of queueing it up to run later.
Linux Tips & Tricks | © ngelinux.com | 8/31/2026
