【问题标题】:Laravel Job Batching unable to cancelLaravel 作业批处理无法取消
【发布时间】:2021-01-27 21:19:35
【问题描述】:

我有一个简单的 laravel 作业批处理,我的问题是当批处理中的一个队列失败并抛出异常时,即使我添加了取消方法,它也不会停止或取消批处理的执行,仍在处理下一个队列。

这是我的句柄和失败的方法

public function handle()
{
    if ($this->batch()->cancelled()) {
        return;
    }
    
    $csv_data = array_map('str_getcsv', file($this->chunk_directory));
    foreach ($csv_data as $key => $row) {
        if(count($this->header) != count($row)) {
            $data = array_combine($this->header, $row);
        } else {
            $this->batch()->cancel();
            throw new Exception("Your file doesn't match the number of headers like your product header");
        }
    }

}

public function failed(\Exception $e = null)
{
    broadcast(new QueueProcessing("failed", BatchHelpers::getBatch($this->batch()->id)));
}

这是我的命令行结果

[2021-01-11 01:17:57][637] Processing: App\Jobs\ImportItemFile
[2021-01-11 01:17:57][637] Failed:     App\Jobs\ImportItemFile
[2021-01-11 01:17:58][638] Processing: App\Jobs\ImportItemFile
[2021-01-11 01:17:58][638] Processed:  App\Jobs\ImportItemFile

【问题讨论】:

  • 我不熟悉批处理,但我建议您在取消批处理后尽量不要抛出异常,以防在作业终止时发生取消
  • 或者也许我在取消批处理之前把抛出的异常,我这样做是为了记录队列异常,这样我就可以在仪表板上显示每个队列失败的描述,但还是一样

标签: laravel queue


【解决方案1】:

来自Laravel 8 Queue 文档:

当批处理中的某个作业失败时,Laravel 会自动将该批处理标记为“已取消”

所以默认行为是整个批次被标记为“已取消”并停止执行(注意当前正在执行的作业不会停止)。 在您的情况下,如果批处理继续执行,也许您在创建批处理时打开了allowFailures() 选项?

顺便说一句,您不需要调用cancel() 方法。当抛出异常时,给定的作业已经“失败”并且整个批次取消。 在取消方法之后删除cancel() 行或return(不引发异常)。 (见Cancelling batches

【讨论】:

    猜你喜欢
    • 2022-01-07
    • 1970-01-01
    • 2021-10-18
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    相关资源
    最近更新 更多