Skip to content

Unable to prevent the creation of the same in a queue #42297

@ukenpachi

Description

@ukenpachi

Using version 8.2.3 I am only trying to dispatch a unique job to a queue. In app/Console/Kernel I have sent a schedule to $schedule->job(new myJob(), 'high')->everyMinute(); this runs every minutes.
In the job itself I have added the ShouldBeUnique interface class in myJob class I even added

public function uniqueId() { 
   return $this->process->id();
}

when my cron job runs for php artisan schedule:run, this is still creating multiple jobs in the queue causing my 3 workers to pick up both jobs at the same time and causing issues.

https://laravel.com/docs/8.x/queues#unique-jobs clearly says

"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. This
interface does not require you to define any additional methods on
your class:"

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Throwable;

class myJob implements ShouldQueue, ShouldBeUnique
{
    use InteractsWithQueue, Queueable, SerializesModels;
    
    private $process;

    public function __construct($process){
       $this->process=$process;
    }
    public function uniqueId() { 
       return $this->process->id();
    }
    
    
    public function handle()
    {
       //some code here
    }

    public function failed(Throwable $exception)
    {
    // Send user notification of failure, etc...
    }
  }

use case

 //controller
public function test()
{
    $x = 1;

    while($x <= 3) {
        $this->dispatch(new newJob());
        $x++;
    }
}

public function test2()
{
    $x = 1;

    while($x <= 3) {
        dispatch(new newJob())->onQueue('high');
        $x++;
    }
}

 public function test3()
{
    $x = 1;

    while($x <= 3) {
        $job = (new newJob())->onQueue('high');
        $this->dispatch($job);
        $x++;
    }
}

![image](https://user-images.githubusercontent.com/5822229/167354206-ae611aa8-66eb-4ea0-aeae-388154655165.png)

those 3 example methods still create dispatch jobs in the jobs table. So how does `ShouldBeUnique` be used?
I'm I missing something?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions