Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Job is already in queue using Laravel 5 and Redis

I've implemented a jobs queue a few days ago and I've been experiencing problems with duplication, I'm currently working with Redis and followed the Laravel's official tutorial.

In my case, whenever someone goes to the homepage, a job is sent to the queue, lets take this example:

HomeController's index() :

public function index()
{
    if(/*condition*/){
          //UpdateServer being the job
          $this->dispatch(new UpdateServer());
    }
}

Since this task takes about 10 seconds to complete, if there's n requests to my homepage while the task is being processed, there will be n more of the same job in queue, resulting in unexpected results in my Database.

So my question is, is there any way to know if a certain job is already in queue?

like image 593
Micael Sousa Avatar asked Aug 01 '15 01:08

Micael Sousa


People also ask

Is there any relation between Redis and Laravel queues?

Laravel has a unified queueing API that lets you choose from various technologies such as Redis, Amazon SQS, Beanstalkd, or even an old-fashioned relational database system.

How do I know if my Laravel queue is working?

$this->mailer->queue($view, $data, function ($message) use ($toEmail, $toName, $subject) { $message ->to($toEmail, $toName) ->subject($subject); }); This will successfully run, but if the queue is not 'listening', the job gets pushed on to the job table, forever. I am looking for something like \Queue::isListening();

How does Redis queue work Laravel?

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.


2 Answers

I know it's very old question, but I'm answering it for future Google users.

Since Laravel 8 there is the "Unique Jobs" feature - https://laravel.com/docs/8.x/queues#unique-jobs.

like image 117
SentalPL Avatar answered Oct 16 '22 13:10

SentalPL


For anyone wondering why

Queue::size('queueName');

is not the same size as

Redis::llen('queues:queueName');

is because Laravel uses 3 records to count the size of a queue, so if you want the true number of jobs in the queue you must do:

Redis::lrange('queues:queueName', 0, -1);
Redis::zrange('queues:queueName:delayed', 0, -1);
Redis::zrange('queues:queueName:reserved', 0, -1);

Now you can evaluate if your desired input is in one of those queues and act according.

like image 25
iRynoh Avatar answered Oct 16 '22 15:10

iRynoh