Stop cron jobs from overlapping and killing your CPU
Cron & Task Scheduling (Cron/Systemd Timers/At)
Stop cron jobs from overlapping and killing your CPU
🧩 The Challenge
Ever had a backup script that took longer than expected to run, only to have a second instance trigger and turn your server into a space heater? I’ve spent more than one late night cleaning up after lock files that didn’t actually lock.
💡 The Fix
Use flock to wrap your cron commands so they only run one instance at a time. It’s the easiest way to ensure the new job waits for the old one to finish or just gives up gracefully.
* * * * * flock -n /tmp/my-script.lock /usr/local/bin/my-script.sh
⚙️ Why It Works
This utility manages a file lock on a specific file descriptor, meaning if the lock is already held by another process, the new one hits the exit signal immediately. By using the -n flag, you tell the script to bail out rather than sitting around and clogging up the process table.
🚀 Pro-Tip: Use a dedicated directory like /run/lock for these instead of /tmp so a random reboot or cleanup script doesn’t delete your lock file.
Linux Tips & Tricks | © ngelinux.com | 10/10/2026
