A worker receiving SIGTERM should finish the current job, stop consuming and exit cleanly.
What It Does and When to Use It
Set a signal flag and stop fetching new work after the current task. 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. Signal handlers must avoid unsafe long work and should not acknowledge unfinished jobs.
Example 1: Basic Operation
Set a signal flag and stop fetching new work after the current task.
<?php
if (!function_exists('pcntl_signal')) throw new RuntimeException('PCNTL required in Unix CLI');
$stop=false;
pcntl_async_signals(true);
pcntl_signal(SIGTERM, static function () use (&$stop): void { $stop=true; });
while (!$stop) { usleep(100000); /* Poll broker for one job here. */ }
echo 'Worker stopped accepting jobs';
Example 2: Behavior and Validation
Acknowledge the message after success, not immediately on delivery.
<?php
$inFlight=true;
try { /* Process an acknowledged job only after it succeeds. */ }
finally { if ($inFlight) error_log('Job completion must be confirmed'); }
Practical Example: Application Use
Check PCNTL availability and supervisor grace time before deployment.
php -m | grep pcntl
systemctl show php-worker -p TimeoutStopUSec
Important Behavior and Edge Cases
The second example highlights: Acknowledge the message after success, not immediately on delivery. The practical example adds: Check PCNTL availability and supervisor grace time before deployment.
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 | Signal handlers must avoid unsafe long work and should not acknowledge unfinished jobs. |
Key Takeaways
- A worker receiving SIGTERM should finish the current job, stop consuming and exit cleanly.
- Check PCNTL availability and supervisor grace time before deployment.
- Acknowledge completed work and use idempotency to make retries safe.