Site icon New Generation Enterprise Linux

Stop cron from running your jobs on top of each other

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

Stop cron from running your jobs on top of each other

🧩 The Challenge

Ever had a backup script that hangs, only to have the next cron run trigger and double your load until the server turns into a space heater? I’ve spent way too many mornings cleaning up locked database files because of exactly this mess.

💡 The Fix

Use flock to wrap your shell commands so the script refuses to run if an instance is already holding the lock file. It keeps your concurrency in check without needing complex PID file management.

* * * * * /usr/bin/flock -n /tmp/my_script.lock /usr/local/bin/my_script.sh

⚙️ Why It Works

Setting the -n flag tells flock to exit immediately if the lock is held, which stops cron from queuing up a pile of stale processes. It’s a simple file-based mutex that survives crashes much better than trying to parse pgrep output.

🚀 Pro-Tip: Use a dedicated directory like /var/lock/app-name for your lock files instead of /tmp to avoid cleanup scripts accidentally nuking them.

Linux Tips & Tricks | © ngelinux.com | 10/8/2026

0 0 votes
Article Rating
Exit mobile version