Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

queue

laravel

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?

like image 894
Faramarz Salehpour Avatar asked Jan 17 '17 09:01

Faramarz Salehpour


People also ask

How do Laravel queues work?

Laravel queues provide a unified API across a variety of different queue backends, such as Beanstalk, Amazon SQS, Redis, or even a relational database. Queues allow you to defer the processing of a time consuming task, such as sending an email, until a later time.

What is Dispatch in Laravel?

# dispatch($command)The dispatch helper function can be used to push a new job onto the job queue (or dispatch the job). The function resolves the configured Illuminate\Contracts\Bus\Dispatcher implementation from the Service Container and then calls the dispatch method in the Dispatcher instance.


2 Answers

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.

like image 58
sisve Avatar answered Oct 17 '22 20:10

sisve


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;
}
like image 20
Abishek Biji Avatar answered Oct 17 '22 20:10

Abishek Biji