How to prioritize queues in Laravel 5.3 events

There is no predefined interface for changing queue for event listeners in Laravel 5.3. By default, it is always taken from your config.

My solution:

namespace App\Listeners;/**
* Class BaseListener
*/
abstract class BaseListener
{
/**
* Detects if class has queue or delay parameter
* If has queue parameter than pushes to certain queue
*
*
@param $queue
*
@param $job
*
@param $data
*
@return mixed
*/
public final function queue($queue, $job, $data)
{
if (isset($this->queue, $this->delay)) {
return $queue->laterOn($this->queue, $this->delay, $job, $data);
}

if (isset($this->queue)) {
return $queue->pushOn($this->queue, $job, $data);
}

if (isset($this->delay)) {
return $queue->later($this->delay, $job, $data);
}

return $queue->push($job, $data);
}
}

One more abstract class for high priority listeners:

namespace App\Listeners;

/**
* Class HighPriorityListener
*
*
@package App\Listeners
*/
abstract class HighPriorityListener extends BaseListener
{
/**
* Queue name
*
*
@var string
*/
protected $queue = 'high';
}

Now you can extend your listeners. Example:

class SendEmail extends HighPriorityListener implements ShouldQueue
{

/**
* Handle the event.
*
*
@param NewMessageReceived $event
*
@return void
*/
public function handle(NewMessageReceived $event)
{
//
}
}

To run a queue worker:

php artisan queue:work — queue=high,default

Now, all jobs from the “high” queue will be executed first. And after that that all from the default

One small tip due to event broadcasting:

use App\Events\Event;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Queue\SerializesModels;

/**
* Class NewMessageReceived
*
*
@package App\Events\Messages
*/
class NewMessageReceived extends Event implements ShouldBroadcastNow
{
// some logic
}

And if you use ShouldBroadcast instead it will push jobs into the queue. It is not convenient if there are a lot of jobs in the queue. You will have to wait until the job is executed.

Hope this information can help someone. I was trying to find some info about it, but couldn’t find a thing.

Do your lara-well =)

--

--

CTO at TenantCloud

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store