如何处理失败的工作 Laravel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49174469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:29:20  来源:igfitidea点击:

How to handle a failed job laravel

laravel

提问by Dell Christopher

I am doing multiple calls to different api's on my cron job, like:

我在我的 cron 工作中多次调用不同的 api,例如:

foreach ($transactions as $transaction) {
    $job = (new SendApplicationToBank($transaction));
    $this->dispatch($job);
}

One transaction has many banks so I am sending a transaction to all banks related:

一笔交易有许多银行,所以我向所有相关银行发送一笔交易:

Job:

工作:

public function handle(){
    try {
        $result = app($bankClass)::sendLoanApplication($this->transaction);
    } catch (Exception $e) {
        //Silent fail
    }
}

The problem is that its failing on the first bank and just keeps retrying.

问题是它在第一家银行上失败了,只是不断重试。

How should go and cofigure so If a job fails just release back to queue and continue the next one ?

应该如何去配置,以便如果一项作业失败,只需释放回队列并继续下一项?

Results:

结果:

php artisan queue:listen

php工匠队列:听

回答by Bj?rn

You should not catch the Exceptionto let the job fail properly. Now you are catching it and doing nothing (//Silent fail)

你不应该抓住Exception让工作正常失败的原因。现在你抓住了它,什么都不做 ( //Silent fail)

You should make a table in your database to catch the failed jobs automatically with:

您应该在数据库中创建一个表以自动捕获失败的作业:

php artisan queue:failed-table

In the script running your queue you should add the number of tries before failing:

在运行队列的脚本中,您应该添加失败前的尝试次数:

php artisan queue:listen --tries=3

It's also smart to add some kind of timeout:

添加某种超时也很聪明:

php artisan queue:listen --tries=3 --timeout=60

And you can also call a webhook on fail by adding a failed method to you job:

您还可以通过向作业添加失败的方法来调用失败时的 webhook:

public function failed()
{
    // Called when the job is failing...
}

回答by Adnan Mumtaz

Running a command with limited tries you can run the following command

运行有限尝试的命令,您可以运行以下命令

php artisan queue:work --retry=3

it will try to run your job only three-time

它只会尝试运行你的工作三次

and programmatically you can use

并以编程方式您可以使用

    public $tries = 3;

in your job class

在你的工作课上

Hope this helps

希望这可以帮助