如何使作业失败并使其跳过 Laravel 队列中的下一次尝试?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41693359/
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 15:08:33  来源:igfitidea点击:

How to fail a job and make it skip next attempts in the queue in Laravel?

laravelqueue

提问by Faramarz Salehpour

I'm writing a simple queue.

我正在写一个简单的队列。

namespace App\Jobs;

use App\SomeMessageSender;

class MessageJob extends Job
{
    protected $to;
    protected $text;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($to, $text)
    {
        $this->to = $to;
        $this->text = $text;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(SomeMessageSender $sender)
    {
    if ($sender->paramsAreValid($this->to, $this->text) {
            $sender->sendMessage($this->to, $this->text);
        }
    else {
        // Fail without being attempted any further
            throw new Exception ('The message params are not valid');
        }
    }
}

If the params are not valid the above code will throw an exception which causes the job to fail but if it still has attempts left, it will be tried again. Instead I want to force this to fail instantly and never attempt again.

如果参数无效,上面的代码将抛出一个异常,导致作业失败,但如果仍有剩余尝试,则会再次尝试。相反,我想强制它立即失败并且不再尝试

How can I do this?

我怎样才能做到这一点?

回答by sisve

Use the InteractsWithQueuetrait and call either delete()if you want to delete the job, or fail($exception = null)if you want to fail it. Failing the job means it will be deleted, logged into the failed_jobs table and the JobFailed event is triggered.

使用InteractsWithQueue特征并delete()在您想要删除作业或fail($exception = null)想要使其失败时调用。作业失败意味着它将被删除,登录到 failed_jobs 表并触发 JobFailed 事件。

回答by Abishek Biji

You can specify the number of times the job may be attempted by using $tries in your job.

您可以通过在作业中使用 $tries 来指定可以尝试作业的次数。

namespace App\Jobs;
use App\SomeMessageSender;

class MessageJob extends Job
{
    /**
    * The number of times the job may be attempted.
    *
    * @var int
    */
    public $tries = 1;
}