Beginners guide to Hangfire
Imagine a website that lets users manage their monthly income and expenditure. It even displays readable charts along with insights for better decision-making. All that this site needs is an input — a spreadsheet with the titles of the ‘expenditure’ and ‘income’ along with the corresponding amounts below it.
Once the spreadsheet is uploaded, the site takes some time to process the information. Now if the user ends up waiting for a long time to get an output, it reduces the overall user experience. It would be nice if the processing task is being taken care of in the background so that users can continue viewing some other information on the website. To achieve this, the website developers need to have background tasks for processing the uploaded information. This can be achieved in .Net programming in multiple ways including in-built techniques such as threads and tasks.
However, in this blog we are going to achieve the same background processing using a third-party library called ‘Hangfire’. Without much ado, let’s understand what is Hangfire and how to implement background tasks using Hangfire.
Table of Content
- What is Hangfire?
- Implement background tasks using Hangfire
- Wrapping up
What is Hangfire?
Hangfire is an open-source framework that can be used to perform background processing in .Net and .Net Core applications. It is mainly used to perform background tasks such as batch/email notification, batch import of files, video/image processing, database maintaining, file purging, etc. Hangfire can be used for background tasks that have high/low CPU consumption, short/long running tasks, recurring jobs, fire and forget, and many more.
Implement background tasks with Hangfire
To use Hangfire, we are going to create an ASP. Net Core-based Web application and that too of the API type.
Create an ASP .Net Web Application and provide a valid name and path for the project.
Choose the template as API and the version as .Net Core as 3.1. Ensure that the ‘Configure for HTTPS’ is checked.
The default API template project structure looks like below.
Let’s install the required packages for Hangfire for implementing in the project. To install the packages, right-click the project and click on Manage NuGet Packages.
Packages to install
- Hangfire.MemoryStorage.Core (This is being used to make use of the Hangfire memory storage inside the code. There is an option to store these and maintain them at the database level (Install-Package Hangfire.SqlServer) which provides the advantage of maintaining the jobs sequence and execution times even when the application is restarted).
Once the packages are installed, then the process shifts to configuring the installed package in the startup services. To do this, open the Startup.cs file, Go to the method ConfigureServices and add the below lines
services.AddHangfire(c => c.UseMemoryStorage()); JobStorage.Current = new MemoryStorage();
You also need to use the reference of the below libraries.
using Hangfire; using Hangfire.MemoryStorage;
Here, we are instantiating Hangfire using the ‘memorystorage’ method of storing the job data.
In the same startup.cs file, in the Configure method, add the below lines
And inside the app.useEndpoints, add endpoints.MapHangfireDashboard();.
This option provides us with a dashboard that can provide real-time data on the background jobs and recurring jobs that are being handled by the Hangfire library.
After configuring the above-mentioned codes, the startup file methods should look something like below.
The Next step is to make use of the Hangfire in the code. To do that, open the controller — weatherforecastcontroller.cs, and at the beginning of the class, declare a global variable to make use of background job client injection.
Make use of the declared variable in the Get method, and add the below lines of code. Here we have implemented a background task that runs every time the endpoint is called.
Now to run the application, open the drop-down menu in the run application option, and select the application name ‘PARTECH_Hangfire’ as the default way to run the application. This will run the application in the desired port and open the console window for the application (which can be used for tracking the logs that we are entering in our code).
Once you run the application, the console window opens up, and points out that the app has started. After a few seconds, it logs the information which we have logged in to the method (that has been Enqueued).
The next step is to create a recurring job using Hangfire in our code.
To do this, in the weatherforecastcontroller.cs file, add the global variable and assign the injected value as we did for the background job client.
Make use of the recurring job variable and add a Log that will be called regularly.
Here the above line is split into three parts, the first part is the jobid, the next is the task that has to be performed and the last is the Cron expression which states the time frame with which the job has to be repeated. In our example, the job will be repeated every one minute.
Run the application to observe the results. Log messages will get executed after every one minute.
Along with these, Hangfire provides an option to visualize the jobs and see the result (success or failure) of each job (day-wise and week-wise).
Also, it provides an option to see the recurring jobs that are being configured through the code and provides the option to delete them at runtime. It also lists the active Hservers that are running. And the dashboard provides a lot more cool features which could be handy for maintaining the jobs.
As we have seen in this blog, Hangfire is quite impressive, easy to install/consume, user friendly (with the dashboard), and can be deployed in no time. In summary, using Hangfire, it is a a very simple task to configure and run the background and recurring jobs.
Originally published at https://www.partech.nl.