阅读(1693) (4)

Laravel 8 任务失败后的清理工作

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

你可以直接在 job 类上定义一个 failed 方法,它允许你在发生故障时执行特定于任务的清理。这是向用户发送警报或还原任务执行的任何操作的最佳位置。导致作业失败的 Throwable 将被传递给 failed 方法:

<?php

namespace AppJobs;

use AppModelsPodcast;
use AppServicesAudioProcessor;
use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateQueueInteractsWithQueue;
use IlluminateQueueSerializesModels;
use Throwable;

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

    protected $podcast;

    /**
     * 创建一个新的任务实例
     *
     * @param  AppModelsPodcast  $podcast
     * @return void
     */
    public function __construct(Podcast $podcast)
    {
        $this->podcast = $podcast;
    }

    /**
     * 执行任务
     *
     * @param  AppServicesAudioProcessor  $processor
     * @return void
     */
    public function handle(AudioProcessor $processor)
    {
        // 处理上传的 podcast...
    }

    /**
     * 任务未能处理
     *
     * @param  Throwable  $exception
     * @return void
     */
    public function failed(Throwable $exception)
    {
        // 给用户发送失败通知, 等等...
    }
}