拉拉维尔作业队列调度现在不会像往常一样失败



我有一项工作来测试失败是如何工作的:

<?php
namespace AppJobs;
use AppApiUser;
use AppHelpersHelper;
use Exception;
use IlluminateBusQueueable;
use IlluminateQueueSerializesModels;
use IlluminateQueueInteractsWithQueue;
use IlluminateContractsQueueShouldQueue;
use IlluminateFoundationBusDispatchable;
class FakeJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private $apiUser;
public function __construct(ApiUser $apiUser) {
$this->apiUser = $apiUser;
}
public function handle() {
throw new Exception('time is even');
}
public function failed(Exception $exception) {
// Send user notification of failure, etc...
$path = storage_path('logs/s3_logs/FakeJob_failed_' . Helper::generateRandomString(5) . '.txt');
file_put_contents($path, $exception->getMessage());
}
}

当我正常调度时,它会转到failed函数并完全按预期写入文件。

但是当我像FakeJob::dispatchNow($apiUser);一样这样做时,它根本不会那样做......

有没有办法执行与请求在同一进程中运行但失败的dispatchNow,就好像它正常排队一样?

因为目前,看起来我唯一的方法就是做这样的事情:

$fakeJob = new FakeJob($apiUser);
try {
$fakeJob->handle();
} catch(Exception $e) {
$fakeJob->failed($e);
}

这是...我猜很好,但并不理想。

如果我没错,调度Now((用于同步运行作业,但不幸的是,它没有调用失败的方法。

如果您希望在作业失败时调用失败的方法,则可以使用以下代码。

FakeJob::dispatch($apiUser)->onConnection('sync');

它将同步运行作业,并执行失败的方法。

查看Laravel代码库(和文档(,dispatchNow()方法在不与任何队列交互的情况下同步执行作业。

https://laravel.com/docs/5.8/queues#synchronous-dispatching

从本质上讲,它只会在您的作业上调用handle()方法,仅此而已。

您对 try/catch 块所做的可能是目前最好的解决方案,但值得将其作为 Laravel 团队的功能请求提出。

一个新的dispatchSync()方法将在未来几个月内发布时在Laravel 8.0中提供.
它将像@Keshari的答案所暗示的那样在同步队列上调度作业。

文档: https://laravel.com/docs/master/queues#synchronous-dispatching
提交: https://github.com/laravel/framework/commit/0b3ed6859046258fba2e0ab3340bdab33e4c82bd

相关内容

最新更新