阅读(4597) (3)

Laravel 8 分发批处理

2021-07-06 09:25:05 更新

要分发任务,你应该使用 Bus facade 的 batch 方法。当然,你可以和批处理的回调结合使用。因此,你可以使用 thencatchfinally 方法来定义批处理的回调,这些回调中每一个在调用时都会接收到一个 IlluminateBusBatch 实例:

use AppJobsProcessPodcast;
use AppPodcast;
use IlluminateBusBatch;
use IlluminateSupportFacadesBatch;
use Throwable;

$batch = Bus::batch([
    new ProcessPodcast(Podcast::find(1)),
    new ProcessPodcast(Podcast::find(2)),
    new ProcessPodcast(Podcast::find(3)),
    new ProcessPodcast(Podcast::find(4)),
    new ProcessPodcast(Podcast::find(5)),
])->then(function (Batch $batch) {
    // 所有任务已成功完成...
})->catch(function (Batch $batch, Throwable $e) {
    // 检测到第一个失败的任务...
})->finally(function (Batch $batch) {
    // 批处理执行完毕...
})->dispatch();

return $batch->id;