Check duplicate jobs having same parameters in Laravel

26 Views Asked by At

I have a cron which triggers thousands of crons on a single execution. So till the jobs are executing, I have some other files, from where the same job might be called with same parameter. I want to prevent that.

So basically, Before triggering a queue, system should check whether the same job with same parameter exists or not on queue. How can i achieve that?

Thank you.

1

There are 1 best solutions below

0
Alex On

As from the Laravel docs:

Sometimes, you may want to ensure that only one instance of a specific job is on the queue at any point in time. You may do so by implementing the ShouldBeUnique interface on your job class.

And more specifically:

In certain cases, you may want to define a specific "key" that makes the job unique or you may want to specify a timeout beyond which the job no longer stays unique. To accomplish this, you may define uniqueId and uniqueFor properties or methods on your job class:

<?php
 
use App\Models\Product;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Queue\ShouldBeUnique;
 
class UpdateSearchIndex implements ShouldQueue, ShouldBeUnique
{
    /**
     * The product instance.
     *
     * @var \App\Product
     */
    public $product;
 
    /**
     * The number of seconds after which the job's unique lock will be released.
     *
     * @var int
     */
    public $uniqueFor = 3600;
 
    /**
     * Get the unique ID for the job.
     */
    public function uniqueId(): string
    {
        return $this->product->id;
    }
}

So you just have to define how to determine your specific job's uniqueness and youre good to go.