Laravel 5: Events – Queue Events Listener

Scheduler: Events – Queue Events Listener


Queue Events Listener – Usage.

Note:
This is just about feeding Event Listeners to a queue.
There is much more about queues to be learned.
By default, queue is set to ‘sync’, which means that jobs are run one after another, which defeats actual purpose queues are designed for.
So, go to this page and find out more about queues.
What is this queue?

Since events are being looped, as registered in EventServiceProvider $listen property, it means each listener gets a chance to do job, and then loop moves to another,

Imagine, that some listeners are busy and it may take them some time to get their task done.

Unless we do something about that, is may force user to wait looooong time for all event triggered tasks (and other jobs) to complete.

In most cases, these heavy lifting tasks can be done in a bit, not right away, so stuff goes fast in front of a user and does not wreck user experience.

That ‘something’ to be done to unload workflow is a queue.
We simply detach some tasks from workflow, stuff it in a queue of tasks to do, first chance system gets.

It sort of resembles jQuery asynchronous actions.


Getting queue ready for action
Lets see our Artisan-generated Listener file:

If you look at it, you will see interface:

All you have to do, is to implement it and Laravel will do the rest.
This is what I mean by implementing:

That is all.

If no exceptions (errors) are thrown when the listener is added to a queue, processed asynchronously, thus not clogging workflow. After it is processed, queued job will automatically be deleted.

important:

As you see above, it is mentioned, that job will be automatically deleted, if there are no problems.
What if there is a problem?

If you run this code in Artisan:

You will get all console queue commands:

You can use e,g, queue:failed  console commands  from within your Laravel project and scheduler to e.g. get yourself a regular report with failed queues.
Or you can store such failed queues in a table.

Interacting with queues manually.

Sometimes, you may want to delete, or release task from queue when you want it and not when Laravel decides to do it.

For that you have some methods provided by trait InteractsWithQueue:

Here are these methods:

  • delete (Delete the job from the queue.)
  • release (Release the job back into the queue. – units used are seconds)
  • attempts (Get the number of times the job has been attempted.)

You can take a look at this Trait here:

Usage is simple.
You use them inside of Listener’s method handle (most likely).

Above code counts attempts and on 10th attempt it deletes task from queue.