A lease or process lock prevents overlapping cron executions of the same maintenance operation.
What It Does and When to Use It
Prevent overlapping runs on one machine. 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. Locks need ownership, expiration and safe release on failure.
Example 1: Basic Operation
Prevent overlapping runs on one machine.
<?php
$lock = fopen(sys_get_temp_dir() . '/cleanup.lock', 'c');
if (!$lock || !flock($lock, LOCK_EX | LOCK_NB)) exit;
try { echo 'Cleanup lease held'; }
finally { flock($lock, LOCK_UN); fclose($lock); }
Example 2: Behavior and Validation
Use a database unique constraint to coordinate more than one worker.
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE jobs (job_key TEXT PRIMARY KEY)');
$stmt = $pdo->prepare('INSERT OR IGNORE INTO jobs (job_key) VALUES (?)');
$stmt->execute(['daily:2026-10-17']);
echo $stmt->rowCount() === 1 ? 'First run' : 'Duplicate';
Practical Example: Application Use
Derive a stable job identifier that can be enforced by a unique index.
<?php
$key = 'invoice:run:' . gmdate('Y-m-d');
echo hash('sha256', $key);
Important Behavior and Edge Cases
The second example highlights: Use a database unique constraint to coordinate more than one worker. The practical example adds: Derive a stable job identifier that can be enforced by a unique index.
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 | Locks need ownership, expiration and safe release on failure. |
Key Takeaways
- A lease or process lock prevents overlapping cron executions of the same maintenance operation.
- Derive a stable job identifier that can be enforced by a unique index.
- Acknowledge completed work and use idempotency to make retries safe.