Content · Web Development · PHP

Creating CLI Commands for Maintenance Jobs

Dedicated PHP CLI commands make scheduled maintenance observable and safe to rerun.

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

Dedicated PHP CLI commands make scheduled maintenance observable and safe to rerun.

What It Does and When to Use It


Validate CLI arguments and return an exit code for misuse. 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. Validate arguments, return nonzero exit codes on failure and protect destructive operations.

Example 1: Basic Operation


Validate CLI arguments and return an exit code for misuse.

<?php
$action = $argv[1] ?? '';
if (!in_array($action, ['check', 'cleanup'], true)) { fwrite(STDERR, "Usage: php jobs.php check|cleanup\n"); exit(2); }
echo "Requested: $action\n";

Example 2: Behavior and Validation


Support a dry-run mode for potentially destructive maintenance.

<?php
$dryRun = in_array('--dry-run', $argv, true);
foreach (['expired-session-15','expired-session-22'] as $item) {
    echo ($dryRun ? 'Would remove ' : 'Removing '), $item, PHP_EOL;
}

Practical Example: Application Use


Lint, execute and inspect the process exit code from a supervisor.

php -l bin/cleanup.php
php bin/cleanup.php check
printf 'exit=%s\n' "$?"

Important Behavior and Edge Cases


The second example highlights: Support a dry-run mode for potentially destructive maintenance. The practical example adds: Lint, execute and inspect the process exit code from a supervisor.

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 constraintsValidate arguments, return nonzero exit codes on failure and protect destructive operations.

Key Takeaways


  • Dedicated PHP CLI commands make scheduled maintenance observable and safe to rerun.
  • Lint, execute and inspect the process exit code from a supervisor.
  • Acknowledge completed work and use idempotency to make retries safe.
Share this resourceSend this page to someone who may find it useful.