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
| 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 | Validate 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.