阅读(4868) (0)

Laravel 8 定义批处理任务

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

要构建可批处理的任务,你应该先 创建任务
然后将 Illuminate\Bus\Batchable trait 添加到任务类,该 trait 提供了对 batch 方法的访问,该方法可用于检索任务当前执行的批处理:

<?php

namespace App\Jobs;

use App\Models\Podcast;
use App\Services\AudioProcessor;
use Illuminate\Bus\Batchable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessPodcast implements ShouldQueue
{
    use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 执行任务
     *
     * @return void
     */
    public function handle()
    {
        if ($this->batch()->cancelled()) {
            // 检测到批处理取消...

            return;
        }

        // 批处理任务执行...
    }
}