A robust worker combines signal-driven drain, retry limits and explicit job acknowledgments.
What It Does and When to Use It
A CLI consumer finishes or requeues in-flight work after it receives a stop signal. 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. Never acknowledge a message before work commits, or the job may be lost.
Example 1: Basic Operation
A CLI consumer finishes or requeues in-flight work after it receives a stop signal.
<?php
$stop=false;
if (function_exists('pcntl_signal')) { pcntl_async_signals(true); pcntl_signal(SIGTERM,static function () use (&$stop) {$stop=true;}); }
while (!$stop) { /* Fetch one job, process, then acknowledge. */ break; }
echo 'No further messages will be fetched';
Example 2: Behavior and Validation
Send permanently failing jobs for inspection once retry limits are reached.
<?php
$job=['id'=>12,'attempt'=>3]; $limit=5;
$action=$job['attempt'] >= $limit?'dead_letter':'requeue';
echo $action;
Practical Example: Application Use
Apply jitter for transient errors and keep the work idempotent.
<?php
$message=['id'=>'task:204','attempt'=>2];
$delayMs=random_int(0,min(30000,250*2**$message['attempt']));
echo 'Next attempt in ', $delayMs,' ms';
Important Behavior and Edge Cases
The second example highlights: Send permanently failing jobs for inspection once retry limits are reached. The practical example adds: Apply jitter for transient errors and keep the work idempotent.
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 | Never acknowledge a message before work commits, or the job may be lost. |
Key Takeaways
- A robust worker combines signal-driven drain, retry limits and explicit job acknowledgments.
- Apply jitter for transient errors and keep the work idempotent.
- Acknowledge completed work and use idempotency to make retries safe.