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

£可爱£侵袭症+ 提交于 2020-07-18 11:52:41

问题


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?


回答1:


Use the InteractsWithQueue trait 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.




回答2:


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

namespace App\Jobs;
use App\SomeMessageSender;

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


来源:https://stackoverflow.com/questions/41693359/how-to-fail-a-job-and-make-it-skip-next-attempts-in-the-queue-in-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!