Content · Web Development · PHP

Gracefully Shutting Down a PHP Queue Worker

A worker receiving SIGTERM should finish the current job, stop consuming and exit cleanly.

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

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


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