Stop your cron jobs from running over each other

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

Stop your cron jobs from running over each other

🧩 The Challenge

Ever had a data sync job take way too long, only to have the next one kick off five minutes later and lock your database? I have, and fixing the resulting corruption is a total nightmare I never want to repeat.

💡 The Fix

Use the flock command to wrap your script so it refuses to run if an instance is already active. It keeps your tasks from piling up into a giant, messy race condition.

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

⚙️ Why It Works

This works by grabbing an advisory lock on a specific file before executing your command. If the lock is already held, the -n flag tells the script to exit immediately instead of queuing up or stomping on the running process.

🚀 Pro-Tip: Use a lock file in /run/lock instead of /tmp if you want to be extra careful about filesystem cleanup.

Linux Tips & Tricks | © ngelinux.com | 12/4/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted