Site icon New Generation Enterprise Linux

Stop crontab from running every copy of your script at the same time

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

Stop crontab from running every copy of your script at the same time

🧩 The Challenge

We have all had that moment where a maintenance script takes longer than expected to run and a new cron job kicks off while the first one is still chewing through data. Next thing you know, your server is crawling because you have five instances of a resource-heavy process fighting for the same locks.

💡 The Fix

Use the flock utility to ensure that only one instance of your job is active at any given time. It acts like a gatekeeper for your scripts so you don’t have to manually manage state files or PID traps.

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

⚙️ Why It Works

Setting the -n flag tells flock to fail immediately if it can’t grab the lock, which effectively skips the execution for that cycle rather than queuing up a backlog of zombie processes. It is way cleaner than writing custom logic to check if a process is already running.

🚀 Pro-Tip: Always put your lock file in /var/lock/ if you have write access; /tmp can get cleared on reboot by systemd-tmpfiles.

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

0 0 votes
Article Rating
Exit mobile version