Skip to content

Commit d786e74

Browse files
authored
[8.x] Add unfinished option to PruneBatchesCommand (#36877)
* Updated pruning batches * Add unfinished option to PruneBatchesCommand * Fix description
1 parent a227942 commit d786e74

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

src/Illuminate/Bus/DatabaseBatchRepository.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,29 @@ public function prune(DateTimeInterface $before)
255255
return $totalDeleted;
256256
}
257257

258+
/**
259+
* Prune all of the unfinished entries older than the given date.
260+
*
261+
* @param \DateTimeInterface $before
262+
* @return int
263+
*/
264+
public function pruneUnfinished(DateTimeInterface $before)
265+
{
266+
$query = $this->connection->table($this->table)
267+
->whereNull('finished_at')
268+
->where('created_at', '<', $before->getTimestamp());
269+
270+
$totalDeleted = 0;
271+
272+
do {
273+
$deleted = $query->take(1000)->delete();
274+
275+
$totalDeleted += $deleted;
276+
} while ($deleted !== 0);
277+
278+
return $totalDeleted;
279+
}
280+
258281
/**
259282
* Execute the given Closure within a storage specific transaction.
260283
*

src/Illuminate/Queue/Console/PruneBatchesCommand.php

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Carbon\Carbon;
66
use Illuminate\Bus\BatchRepository;
7+
use Illuminate\Bus\DatabaseBatchRepository;
78
use Illuminate\Bus\PrunableBatchRepository;
89
use Illuminate\Console\Command;
910

@@ -14,7 +15,9 @@ class PruneBatchesCommand extends Command
1415
*
1516
* @var string
1617
*/
17-
protected $signature = 'queue:prune-batches {--hours=24 : The number of hours to retain batch data}';
18+
protected $signature = 'queue:prune-batches
19+
{--hours=24 : The number of hours to retain batch data}
20+
{--unfinished= : The number of hours to retain unfinished batch data }';
1821

1922
/**
2023
* The console command description.
@@ -30,14 +33,24 @@ class PruneBatchesCommand extends Command
3033
*/
3134
public function handle()
3235
{
33-
$count = 0;
34-
3536
$repository = $this->laravel[BatchRepository::class];
3637

38+
$count = 0;
39+
3740
if ($repository instanceof PrunableBatchRepository) {
3841
$count = $repository->prune(Carbon::now()->subHours($this->option('hours')));
3942
}
4043

4144
$this->info("{$count} entries deleted!");
45+
46+
if ($unfinished = $this->option('unfinished')) {
47+
$count = 0;
48+
49+
if ($repository instanceof DatabaseBatchRepository) {
50+
$count = $repository->pruneUnfinished(Carbon::now()->subHours($this->option('unfinished')));
51+
}
52+
53+
$this->info("{$count} unfinished entries deleted!");
54+
}
4255
}
4356
}

0 commit comments

Comments
 (0)