Cron & Task Scheduling (Cron/Systemd Timers/At)
Stop your cron jobs from running if the last one is still stuck
đź§© The Challenge
Everyone has had that one backup script that hangs during a bad network patch, only for the next cron job to kick off and turn your server into a pile of CPU-choking duplicate processes. It’s an absolute nightmare to clean up, and nobody tells you that cron doesn’t care if your last execution is still running.
đź’ˇ The Fix
Use flock to place a lock file on your task so that if the first instance hasn’t finished, the subsequent ones just bail out instead of stacking up. It keeps your process list sane and prevents resource exhaustion.
* * * * * /usr/bin/flock -n /tmp/my_script.lock /usr/local/bin/my_script.sh
⚙️ Why It Works
The -n flag tells flock to exit immediately with a failure code if it can’t acquire the lock, which effectively skips the execution for that cycle. Since it’s handled at the kernel level, you don’t have to worry about race conditions or checking PIDs manually.
🚀 Pro-Tip: Always put your lock file in a dedicated directory rather than /tmp to avoid local users deleting it out from under you.
Linux Tips & Tricks | © ngelinux.com | 8/24/2026
