Prevent Duplicate Cron Jobs with Linux flock: A Step‑by‑Step Guide
This article demonstrates how cron jobs can overlap when a script runs longer than its schedule, and shows how to use Linux's flock file lock to ensure only one instance of the script runs at a time, preventing execution conflicts.
Example
To simulate a conflict, a PHP script that loops 180 times, prints messages and sleeps one second (≈3 minutes) is created (test.php). A crontab entry runs it every minute: * * * * * php /root/test.php >> /root/test.log After a minute, the process appears; after another minute, another instance appears, showing duplicate execution.
Solution
Use Linux flock file locking to ensure only one instance runs.
Replace the crontab entry with:
* * * * * flock -xn /tmp/mytest.lock -c 'php /root/testflock.php >> /root/test.log'Now only a single testflock.php process is observed.
flock Explanation
The flock command obtains an exclusive lock before running the task. If the lock cannot be acquired, the command exits without running, preventing overlap.
Key options used: -x, --exclusive : acquire an exclusive lock. -n, --nonblock : fail immediately if the lock is not available. -c, --command : execute the given command in a shell.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
