Skip to content

Queuing Background Jobs with Coravel

Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.

Learn more about Software Architecture & Design.
Join thousands of developers getting weekly updates to increase your understanding of software architecture and design concepts.


Coravel

In one of my live streams on my YouTube Channel, I took a look at using Coravel to refactor some code that was sending out an email. Emailing is a good example of something that can be created as a background job that frees up your web application to return a result quicker to the client.

Coravel

Coravel gives you a zero-configuration queue that runs in-memory to offload long-winded tasks to the background instead of making your users wait for their HTTP request to finish!

It’s pretty easy to get started to run background jobs with Coravel in your ASP.NET Core apps, or really any app that is using Microsoft.Extensions.DependencyInjection and IServiceCollection. Simply call AddQueue() from ConfigureServices()

Background Job

In my live stream, I refactored the code used for sending a verification email to use Coravel to enqueue a background job to be handled in a separate thread. Here’s what I did to make that happen.

The first step is to create a class that implements IInvocable and in my use case also implements IInvocableWithPayload<T>, which also allows us to pass data (eg, parameters) to our background job.

This class will be constructed and invoked when our background job is enqueued. Because we’re using the MS DI, you are free to inject dependencies via the constructor, so as long as they are registered.

What that looks like in its simplistic form:

Now to call the new invocable as a background job, you will need to inject the IQueue into your Controller (or any class). From there you can call IQueue.QueueInvocableWithPayload

To tie things all up, you need to register your invocable in your ConfigureServices so Coravel can use the MS DI to create a new instance of it.

More Coravel

Coravel actually does a lot more than just queueing background jobs. Task Scheduling, Caching, Event Broadcasting, and Emailing. Check out the project on GitHub.

Links

Learn more about Software Architecture & Design.
Join thousands of developers getting weekly updates to increase your understanding of software architecture and design concepts.


Leave a Reply

Your email address will not be published. Required fields are marked *