jlmmns's avatar
Level 12

Event Listeners vs. Jobs

Hi all,

I've implemented realtime broadcasted events using Redis and Socket.io.

Everyting is working, but the process has lead me to some confusion about Event Listeners, and Jobs.

The way I understand it, Jobs are used to process things in the background, on a queue.

Event Listeners are used to process things, depending on which Event has occured.

It seems Event Listeners are also put on a queue, by default.

So, now my question is:
Why would you create an Event Listener, if you can just fire a Job from the Event itself?
Because if you create an Event Listener, it would just act as a Job, right?

Any suggestions or clarifications?

0 likes
5 replies
mina's avatar
mina
Best Answer
Level 2

Jobs are bits of code that will extend the normal MVC functionality, and that can be used in several places. Apart from being queued (because Jobs can actually run synchronously), if you feel you are repeating bits of code, then use a Job. Also if your Controllers are becoming huge with about 10 dependencies, try to go slim, and abstract them in Jobs. Jobs needs to be called in their specific location in the code to be triggered.

For Event Listeners, they have a different role, Listeners can be considered as Jobs waiting for specific event to take place. Listeners will be triggered once an Event is created, you do not call Listeners.

For example, a Job can a simple script that creates a report every night. Listener, can be a script that sends an email once a new user is created. And here, you can trigger many Listeners for a single Event, without calling them one by one.

Use Jobs to abstract, use Listeners, when you need to perform an action based on system wide Event.

Both Listeners and Jobs can run synchronously or asynchronously, depending on your application.

22 likes
jlmmns's avatar
Level 12

@mina Thanks for the clarification! Makes sense.

Bonus question:
Would it also be possible to fire a Job, inside of an already queued Event Listener?

Edit: Found my answer in a tutorial from Jeffrey!

2 likes
stephen.talari's avatar

I tried to include this in Listener use App\Http\Controllers\Controller and call this->dispatch($job) It worked!

Is Jeffrey answer different from this ? (i don't have access to lessons :-( )

jlmmns's avatar
Level 12

@stephen.talari You only need to include the dispatchesJobs trait that controllers use.

It's not necessary to include a whole controller.

1 like
mina's avatar

Hello @jlmmns, sorry for the late reply, I see you found an answer, anyways, can include displatchesJobs trait anywhere in your code, then fire Jobs from there.

3 likes

Please or to participate in this conversation.