mercredi 27 juin 2018

Laravel: How can a queued job move itself to failed_jobs on fail?

I have a queueable Job that creates a new user...

<?php

namespace App\Jobs;

...

class CreateNewUser implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /** @var array */
    public $newUserData;

    public function __construct($newUserData)
    {
        $this->newUserData = $newUserData;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $email = $this->newUserData['email'];
        if (User::whereEmail($email)->count()) {
            // TODO: Make this job fail immediately
            throw new UserWithEmailExistsException('User with email ' . $email . ' already exists');
        }

        ...
    }
}

It's a queued job because we batch process CSVs to load in many users at a time, each one requiring an entry in 2 tables plus multiple entries in roles and permissions tables. Too slow to do synchronously.

I have a check at the start of the handle() method to see if a user with the same email address has not already been created (because potentially several jobs could be queued to create users with the same email) and it throws a custom Exception if it does.

If that check fails, I don't ever want the queue worker to attempt this job again because I know it will continue to fail indefinitely, it's a waste of time to re-attempt even once more. How can I manually force this job to fail once and for all and move over to the failed jobs table?

P.S. I have found the SO answer about the fail() helper but that still does not immediately move the job from jobs to failed_jobs.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire