Skip to content

Commit

Permalink
[8.x] Add unfinished option to PruneBatchesCommand (#36877)
Browse files Browse the repository at this point in the history
* Updated pruning batches

* Add unfinished option to PruneBatchesCommand

* Fix description
  • Loading branch information
driesvints authored Apr 5, 2021
1 parent a227942 commit d786e74
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
23 changes: 23 additions & 0 deletions src/Illuminate/Bus/DatabaseBatchRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
19 changes: 16 additions & 3 deletions src/Illuminate/Queue/Console/PruneBatchesCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Carbon\Carbon;
use Illuminate\Bus\BatchRepository;
use Illuminate\Bus\DatabaseBatchRepository;
use Illuminate\Bus\PrunableBatchRepository;
use Illuminate\Console\Command;

Expand All @@ -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.
Expand All @@ -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!");
}
}
}

0 comments on commit d786e74

Please sign in to comment.