|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Doppar\Queue\Commands; |
| 4 | + |
| 5 | +use Phaseolies\Console\Schedule\Command; |
| 6 | +use Doppar\Queue\QueueManager; |
| 7 | +use Doppar\Queue\Models\FailedJob; |
| 8 | + |
| 9 | +class QueueRetryCommand extends Command |
| 10 | +{ |
| 11 | + /** |
| 12 | + * The name of the console command. |
| 13 | + * |
| 14 | + * @var string |
| 15 | + */ |
| 16 | + protected $name = 'queue:retry {--id=}'; |
| 17 | + |
| 18 | + /** |
| 19 | + * The command description. |
| 20 | + * |
| 21 | + * @var string |
| 22 | + */ |
| 23 | + protected $description = 'Retry failed job(s) by ID or all if no ID is provided'; |
| 24 | + |
| 25 | + /** |
| 26 | + * Execute the console command |
| 27 | + * Example: php pool queue:retry --id=4 |
| 28 | + * |
| 29 | + * @return int |
| 30 | + */ |
| 31 | + protected function handle(): int |
| 32 | + { |
| 33 | + $id = $this->option('id'); |
| 34 | + $manager = app(QueueManager::class); |
| 35 | + |
| 36 | + if ($id) { |
| 37 | + return $this->retryJobById($manager, $id); |
| 38 | + } |
| 39 | + |
| 40 | + FailedJob::query() |
| 41 | + ->cursor(function (FailedJob $failedJob) use ($manager) { |
| 42 | + $this->retryFailedJob($manager, $failedJob); |
| 43 | + }); |
| 44 | + |
| 45 | + return Command::SUCCESS; |
| 46 | + } |
| 47 | + |
| 48 | + protected function retryJobById(QueueManager $manager, int $id): int |
| 49 | + { |
| 50 | + $failedJob = FailedJob::find($id); |
| 51 | + |
| 52 | + if (!$failedJob) { |
| 53 | + $this->error("Failed job with ID {$id} not found."); |
| 54 | + return Command::FAILURE; |
| 55 | + } |
| 56 | + |
| 57 | + if ($this->retryFailedJob($manager, $failedJob)) { |
| 58 | + return Command::SUCCESS; |
| 59 | + } |
| 60 | + |
| 61 | + return Command::FAILURE; |
| 62 | + } |
| 63 | + |
| 64 | + protected function retryFailedJob(QueueManager $manager, FailedJob $failedJob): bool |
| 65 | + { |
| 66 | + try { |
| 67 | + $job = $manager->unserializeJob($failedJob->payload); |
| 68 | + $jobClass = get_class($job); |
| 69 | + |
| 70 | + // Reset attempts |
| 71 | + $job->attempts = 0; |
| 72 | + |
| 73 | + // Push back to queue |
| 74 | + $manager->push($job); |
| 75 | + |
| 76 | + // Delete from failed jobs |
| 77 | + $failedJob->delete(); |
| 78 | + |
| 79 | + $this->info("✔ Retried job [{$jobClass}] (ID: {$failedJob->id})"); |
| 80 | + return true; |
| 81 | + } catch (\Throwable $e) { |
| 82 | + $this->error("✖ Failed to retry job ID {$failedJob->id}: " . $e->getMessage()); |
| 83 | + return false; |
| 84 | + } |
| 85 | + } |
| 86 | +} |
0 commit comments