JenuelDev's avatar

In Laravel How to get the ID of a Queue Job?

So I have this code, what I am trying to do is able to get the UUID, so that I can retry it later if it fails.

$sendMailJob = (new SendQueueEmail($mailSent, $filePaths));
$uuid = $sendMailJob->uuid;

// dispatch job
dispatch($sendMailJob);

but of course, this does not work, how can I get the UUID?

0 likes
5 replies
nexxai's avatar

Any failed jobs will end up in the failed_jobs table, so it usually makes more sense to review them and/or schedule them to try again after a certain period of time (for example, if you know the API you're dealing with is flaky sometimes).

1 like
krisi_gjika's avatar

you can configure your queue to retry your jobs as --tries=3 before marking them as failed.

1 like
Snapey's avatar

I would try to make the job itself responsible for deciding what happens next, for instance, dispatching another copy of itself scheduled for a later time.

You can also set an exponential backoff time so that job retries don't all happen immediately

1 like
JenuelDev's avatar
JenuelDev
OP
Best Answer
Level 1

I was able to get the job uuid inside my Queue Job Class under handle function :

public function handle()
    {
        try {
            $uuid = $this->job->uuid(); //
// some codes here

I need to save it so that I can retry it later if it fails or an API throws an error. What I like about this is that the failed Job also saves the error message I can use for debugging and stuffing.

with this I can just create a function like this:

public function retryFailedSent($uuid): JsonResponse
    {
        try {
            $failedJob = DB::table('failed_jobs')->where('uuid', $uuid)->first();
            if (!$failedJob) throw new Exception("Failed Job Not Found!");

            Artisan::call('queue:retry '.$uuid);

            return response()->json(['message' => "Email is being sent."]);
        } catch (Exception $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }
flow96's avatar

For anyone having the same problem and coming here to find a solution - you can use one of the following methods instead to dispatch a job and get the jobId instantly:

$job = new YourJob();
$jobId = Bus::dispatch($job);
// Or
$jobId = Queue::push($job);

It's stated in the Laravel documentation for Tinker in the "usage" section (there is an info box - seems like I am not allowed to post links in here).

2 likes

Please or to participate in this conversation.