Posted by Kinjal Patel on May 24, 2022 17:35
Hangfire with ASP.NET Core
All applications need to do some sort of background work. A repetitive job that we need to do every day or every other day or weekly or monthly. In this article we are going to learn how we can easily implement it using Hangfire.
What Is Hangfire??
Hangfire is an open source library to schedule and execute background jobs in .NET applications. It’s simple to use, well structured, and gives a powerful performance.We can create a simple background process inside the same application pool or thread without creating separate applications.
When To Use Background Processing??
Processing a task in the background means that we can execute it away from the application’s main thread.To keep our applications running smoothly and our users happy, for certain tasks we can utilize a concept called background processing. E.g. we may need to send a notification to our user. We can do that behind the scenes and the user can continue to browse freely.
Hangfire Features
Easy to install
Easy to configure
Nice UI dashboard to check up on our jobs at any time
Open source software and is completely free
Supports multiple queue processing
Background jobs are created in a persistent storage – SQL Server and Redis
Self-maintainable (We don't need to perform manual storage clean-up)
If a job fails, Hangfire will try to run it again as soon as possible.
How does it work?
There are three main components of Hangfire architecture.
Client:
The actual libraries inside our application.
The client creates the job, serializes its definition, and makes sure to store it into our storage (e.g SQL database).
Server:
The server picks up the job definitions from the storage and executes them.
The server can live within our application or can be on another server because it always points to the database storage.
It also keeps our job storage clean of any data that we don’t use anymore.
Storage:
This is our database.
It uses some tables that Hangfire default creates for us.
It stores all the information about our jobs definitions and execution status.
By default, it uses SQL Server, but it also supports RDBMS and NoSQL.
Flow execution
First we need to specify the task in the code.
Then call the appropriate hangfire method to create it.
Based on that the hangfire client creates the job and stores it into the database.
Then hangfire returns the control back to the application so the next code can continue with its execution.
The server picks up the job stored in the storage and creates a background thread to process the job.
Project setup
To start, we will create an ASP.NET Core 6.0 web Application with a project type of web API and call it HangFire.API.
Require packages for hangfire:
Setup the database and update the appsettings.json file.
Program.cs file
Now let’s configure the hangfire in the program.cs file.
Add AddHangfire() method with the SQL Server storage.
Add the Hangfire server with the AddHangfireServer().
Then update our request processing pipeline.
Run the application.
Hangfire will automatically check our storage for the required tables, and if they don’t exist then it will create them first.
Once the application runs successfully, navigate to the https://localhost:7079/hangfire/ hangfire URL.
Create an interface IHangFireJobService.cs and Create some methods in it to understand hangfire jobs.
Create a HangFireJobService.cs file to implement our interface.
Types of Jobs
Fire-And-Forgot Jobs
Executed only once and almost immediately after creation.
Delayed Jobs
Executed only once too, but not immediately, after a certain time interval.
Recurring Jobs
Fire many times on the specified CRON schedule.
Continuations Jobs
Executed when its parent job has been finished.
Batches Jobs
A batch is a group of background jobs that are created atomically and considered as a single entity.
Batch Continuations Jobs
Fired when all background jobs in a parent batch are finished.
Now let’s look at each job in detail.
Fire - And - Forgot Jobs
Create a [HttpGet("/FireAndForgetJob")] endpoint into the controller.
In the controller, we are using the IBackgroundJobClient interface of hangfire.
Here we call the interface’s Enqueue() method of IBackgroundJobClient and pass it our FireAndForgetJobAsync() service method below.
The Enqueue method will create and save job definitions to our storage.
Send the Get request from Swagger.
This will create our first job with Hangfire.
Now check the job in the dashboard.
Go to the Jobs tab and observe our job is available in the Succeeded section.
Delayed Job
Create a [HttpGet("/DelayedJob")] endpoint into the controller.
In the controller, we are again using the IBackgroundJobClient interface of hangfire.
Here we call the interface’s Schedule() method instead of Enqueue() method of the IBackgroundJobClient hangfire interface and pass it our DelayedJobAsync() service method.
Here we added the delay.
The Schedule method will also create the job definition and save it
It will also schedule it in the queue at the specified time.
We scheduled a job with a delay of 60 seconds.
Go to the Job>> Scheduled section.
After 60 seconds it executes successfully and moves to the Succeeded tab.
Recurring Job
Create a [HttpGet("/RecurringJob")] endpoint into the controller.
In the controller,we are using the IRecurringJobManager interface of hangfire.
Here we call the interface’s AddOrUpdate() method of IRecurringJobManager interface and pass it our RecurringJobAsync() service method.
We also need to pass the job id and the CRON interval.
The AddOrUpdate method will create a new job for the first time.
Go to the Recurring tab and observe our job is available.
Here we scheduled our job to repeat at the specified time. so every time the server executes it, it will go to the Succeeded section.
Create a [HttpGet("/ContinuationJob")] endpoint into the controller.
First we will create one Fire and Forget job then
This job will trigger the next job, so we will get the id from the Enqueue() method once it’s created.
Then call the interface ContinueJobWithAsync() method and pass the job id of the created job and call the ContinueJobWithAsync() method
The ContinueJobWithAsync() method will create a chain for our two jobs together.
Output of all the jobs executed
Real World Example using hangfire
Now,let's implement one real world scenario using a Recurring job to send an email.
Write some method to add a simple GET method to send an email using smtp client.
Call it by using AddOrUpdate() method of IRecurringJobManager interface.
You will get the email every 1 minutes!!!!
Note: Not adding here the sample code to send email using SMTP!
Reference: https://www.hangfire.io/
Enjoy coding!!!
Trusted by global clients for a decade of consistent delivery and innovation.
Long-term partners who rely on us for intelligent, reliable solutions.
From complex systems to AI-first applications — every project built to perform.
Toshal is an incredible team to work with. I'm always able to trust their technical proficiency in any project I give them, but where they stand apart is how collaborative and hardworking they are. Anytime we work together, I'm always 100% confident the work will be completed on time and as expected. I love working with Toshal!
We are pleased to recommend our longtime partner, Toshal Infotech Pvt. Ltd. For over a decade, we relied on Ashish’s team at Toshal to provide us with timely development services and expert advice in a range of web technologies and assist us with occasional graphics and design assignments. We look forward to working with this group for many more years.
Toshal Infotech Pvt. Ltd. has been a trusted web development partner for our company for nearly a decade. They are responsive, effective, and so wonderful to work with. We are lucky to have found such a great partnership.
Always a pleasure to work with Toshal Infotech Pvt. Ltd. Great work, fast delivery, pleasant and polite seller. Definitely recommended.
Very helpful seller. Works well and delivers good work. Very happy with everything. Would recommend and will use again.
As always, a pleasure working with you - I can't believe how quick you did this update for me.thank you so much. looking forward to working with you on many more projects to come :)
FANTASTIC service - I'm amazed at how fast they managed to turn this modification to my app around. the level of service and communication was flawless, absolutely brilliant. they are not only good and incredibly skilled at what they do, they are also friendly and have GREAT communication skills. I will definitely be using you again :) thank you
seller is very good and delivered in time..worth buying..
Very happy to work again with them. They are always proactive in solving everything and the communication is great too.
We needed an android app on a deadline. They exceeded our expectations in every way, communication was great, and they worked in a very responsible way. Will definitely work with them again.