Site icon New Generation Enterprise Linux

Stop cron jobs from overlapping and crushing your CPU

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

Stop cron jobs from overlapping and crushing your CPU

🧩 The Challenge

Ever had a data sync script that runs every five minutes, only to have a massive database lock cause it to hang? Before you know it, you have fifty stale processes eating all your RAM and your server is practically catatonic.

💡 The Fix

Use flock to ensure only one instance of your script runs at a time. It’s a clean way to keep your sanity without rewriting your logic to handle PID files manually.

* * * * * /usr/bin/flock -n /tmp/my-script.lock /usr/local/bin/sync-script.sh

⚙️ Why It Works

Adding the -n flag makes the command exit immediately if it can’t grab the lock instead of waiting around in a queue. You keep the system stable and the latest job just skips a beat rather than stacking up.

🚀 Pro-Tip: Always point the lock file to a dedicated directory in /var/lock/ if you want to be pedantic about FHS compliance.

Linux Tips & Tricks | © ngelinux.com | 7/29/2026

0 0 votes
Article Rating
Exit mobile version