Content · Web Development · PHP

Working with Process Locks for PHP Cron Jobs

flock() can guard against concurrent execution of local cron scripts.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 Admin

flock() can guard against concurrent execution of local cron scripts.

What It Does and When to Use It


Use a nonblocking exclusive file lock on a single host. A producer publishes work, a consumer executes it, and the broker or scheduler controls delivery and retries.

Requirements, Inputs and Expected Behavior


Confirm the runtime, extension, environment variables, and permissions before running the examples in production. A local file lock does not coordinate containers across different hosts.

Example 1: Basic Operation


Use a nonblocking exclusive file lock on a single host.

<?php
$handle = fopen(sys_get_temp_dir() . '/import-job.lock', 'c');
 if (!$handle || !flock($handle, LOCK_EX | LOCK_NB)) exit(0);
 try { echo 'Running single-instance import'; }
 finally { flock($handle, LOCK_UN); fclose($handle); }

Example 2: Behavior and Validation


Return a distinct exit code when another instance is already active.

<?php
$file = fopen('/tmp/report-cron.lock', 'c');
 if (!$file || !flock($file, LOCK_EX | LOCK_NB)) { fwrite(STDERR, "Job already running
"); exit(75); }
 try { echo 'Generate report'; }
 finally { flock($file, LOCK_UN); fclose($file); }

Practical Example: Application Use


Schedule a single entry; do not assume local flock covers multiple hosts.

* * * * * /usr/bin/php /srv/app/bin/report.php >> /var/log/report.log 2>&1

Important Behavior and Edge Cases


The second example highlights: Return a distinct exit code when another instance is already active. The practical example adds: Schedule a single entry; do not assume local flock covers multiple hosts.

Comparison with Related Approaches


ApproachWhat changes
Producer, consumer and schedulerA producer publishes work, a consumer executes it, and the broker or scheduler controls delivery and retries.
Choosing safelyAcknowledge completed work and use idempotency to make retries safe.

Common Beginner Mistakes


MistakeCorrect approach
Acknowledging a job before it finishesMark delivery successful only after durable processing succeeds.
Treating retries as harmlessUse idempotency keys and a bounded retry policy with dead-letter handling.
Skipping operational constraintsA local file lock does not coordinate containers across different hosts.

Key Takeaways


  • flock() can guard against concurrent execution of local cron scripts.
  • Schedule a single entry; do not assume local flock covers multiple hosts.
  • Acknowledge completed work and use idempotency to make retries safe.
Share this resourceSend this page to someone who may find it useful.