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
| Approach | What changes |
|---|---|
| Producer, consumer and scheduler | A producer publishes work, a consumer executes it, and the broker or scheduler controls delivery and retries. |
| Choosing safely | Acknowledge completed work and use idempotency to make retries safe. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Acknowledging a job before it finishes | Mark delivery successful only after durable processing succeeds. |
| Treating retries as harmless | Use idempotency keys and a bounded retry policy with dead-letter handling. |
| Skipping operational constraints | A 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.