Content · Web Development · PHP

Preventing Duplicate Scheduled Jobs in PHP

A lease or process lock prevents overlapping cron executions of the same maintenance operation.

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

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


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 constraintsLocks 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.
Share this resourceSend this page to someone who may find it useful.