diff --git a/src/Illuminate/Bus/DatabaseBatchRepository.php b/src/Illuminate/Bus/DatabaseBatchRepository.php index 03d7a3dab3cb..ee544b04223d 100644 --- a/src/Illuminate/Bus/DatabaseBatchRepository.php +++ b/src/Illuminate/Bus/DatabaseBatchRepository.php @@ -255,6 +255,29 @@ public function prune(DateTimeInterface $before) return $totalDeleted; } + /** + * Prune all of the unfinished entries older than the given date. + * + * @param \DateTimeInterface $before + * @return int + */ + public function pruneUnfinished(DateTimeInterface $before) + { + $query = $this->connection->table($this->table) + ->whereNull('finished_at') + ->where('created_at', '<', $before->getTimestamp()); + + $totalDeleted = 0; + + do { + $deleted = $query->take(1000)->delete(); + + $totalDeleted += $deleted; + } while ($deleted !== 0); + + return $totalDeleted; + } + /** * Execute the given Closure within a storage specific transaction. * diff --git a/src/Illuminate/Queue/Console/PruneBatchesCommand.php b/src/Illuminate/Queue/Console/PruneBatchesCommand.php index cc25bc53cfb9..59ea3887b8ab 100644 --- a/src/Illuminate/Queue/Console/PruneBatchesCommand.php +++ b/src/Illuminate/Queue/Console/PruneBatchesCommand.php @@ -4,6 +4,7 @@ use Carbon\Carbon; use Illuminate\Bus\BatchRepository; +use Illuminate\Bus\DatabaseBatchRepository; use Illuminate\Bus\PrunableBatchRepository; use Illuminate\Console\Command; @@ -14,7 +15,9 @@ class PruneBatchesCommand extends Command * * @var string */ - protected $signature = 'queue:prune-batches {--hours=24 : The number of hours to retain batch data}'; + protected $signature = 'queue:prune-batches + {--hours=24 : The number of hours to retain batch data} + {--unfinished= : The number of hours to retain unfinished batch data }'; /** * The console command description. @@ -30,14 +33,24 @@ class PruneBatchesCommand extends Command */ public function handle() { - $count = 0; - $repository = $this->laravel[BatchRepository::class]; + $count = 0; + if ($repository instanceof PrunableBatchRepository) { $count = $repository->prune(Carbon::now()->subHours($this->option('hours'))); } $this->info("{$count} entries deleted!"); + + if ($unfinished = $this->option('unfinished')) { + $count = 0; + + if ($repository instanceof DatabaseBatchRepository) { + $count = $repository->pruneUnfinished(Carbon::now()->subHours($this->option('unfinished'))); + } + + $this->info("{$count} unfinished entries deleted!"); + } } }