Content · Web Development · PHP

PHP Background Worker Graceful Shutdown

Use stop signals and explicit cleanup to give background jobs time to finish safely.

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

Use stop signals and explicit cleanup to give background jobs time to finish safely.

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. If a worker is terminated during a side effect, the queue must support safe retry and deduplication.

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 constraintsIf a worker is terminated during a side effect, the queue must support safe retry and deduplication.

Key Takeaways


  • Use stop signals and explicit cleanup to give background jobs time to finish safely.
  • 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.