Operations 3 min read

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.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Prevent Duplicate Cron Jobs with Linux flock: A Step‑by‑Step Guide

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

task schedulingLinuxPHPcronflockFile Lock
Java High-Performance Architecture
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.