HangFire is an easy way to perform background processing in .NET and .NET Core applications. There isn’t any need to have a separate windows service or any separate process. Hangfire supports all kinds of background tasks – short-running and long-running, CPU intensive and I/O intensive, one shot and recurrent. You don’t need to reinvent the wheel – it is ready to use. In this post, we will see how to integrate HangFire with ASP.NET Core WEB API.
Integrate HangFire With ASP.NET Core WEB API
HangFire uses persistence storage to persist background jobs information. Since all the information is saved in persistent storage, application restarts doesn’t affect the job processing. At the time of writing this post, HangFire uses SQL Server, Redis, PostgreSQL, MongoDB and Composite C1. In this post, I will be using SQL Server. So let’s create an empty database in SQL Server and name it “HangFireDemo”.
Let’s create an ASP.NET Core Web API project. Once the project is created, we need to install HangFire via nuget. You can install it via Package Manager Console and executing below command.
Install-Package HangFire
Or you can also install via NuGet Pacakge Manager. Search for “HangFire” and click install.
Okay. So HangFire is installed. Now let’s configure it. Open Startup.cs, navigate to ConfigureServices
method and add HangFire service to middleware. Here we must provide HangFireDemo database connection string, which I have put in web.config.
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); string sConnectionString = ConfigurationManager.ConnectionStrings["Hangfire"].ConnectionString; services.AddHangfire(x => x.UseSqlServerStorage(sConnectionString)); services.AddMvc(); }
Once the service is configured, navigate to Configure
method and add highlighted line. app.UseHangfireDashboard();
will setup a dashboard where you could find all the information about your background jobs. And app.UseHangfireServer();
will setup a new instance of BackgroundJobServer, responsible for background job processing.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseApplicationInsightsRequestTelemetry(); app.UseApplicationInsightsExceptionTelemetry(); app.UseHangfireDashboard(); app.UseHangfireServer(); app.UseMvc(); }
Now run the app. To see HangFire Dashboard, hit the http://<site-url>/hangfire URL to see the Dashboard.
You can see a list of jobs, servers, real-time graph and other things in DashBoard. By default, Hangfire maps the dashboard to /hangfire
URL, but you can change it.
// Map the Dashboard to the root URL app.UseHangfireDashboard(""); // Map to the '/dashboard' URL app.UseHangfireDashboard("/dashboard");
If you expand “HangFireDemo” database, then you can see set of tables created in the Database for storing background job information.
It’s really easy to integrate HangFire. But HangFire dashboard works only for local requests. In order to use it in production, we need to implement authorization. To implement authorization, we use IAuthorizationFilter
interface and implement OnAuthorization
method to implement own authorization.
public class CustomAuthorizeFilter : IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) { //logic to authorize user } }
And modify Startup.cs to pass this filter to UseHangfireDashboard
method.
app.UseHangfireDashboard("/dashboard", new DashboardOptions { AuthorizationFilters = new[] { new CustomAuthorizeFilter() } });
This will ensure that Hangfire dashboard running in production only after successful authorization. Now, let’s create a background job. With Free version of HangFire, you can create following types of jobs.
- Fire-and-forget: Fire-and-forget jobs are executed only once and almost immediately after creation.
- Delayed: Delayed jobs are executed only once too, but not immediately, after a certain time interval.
- Recurring: Recurring jobs fire many times on the specified CRON schedule.
- Continuations: Continuations are executed when its parent job has been finished.
For the demonstration purposes, create a Recurring Task which will write something to output window every minute. So add the following line in Startup.cs -> Configure()
, below the app.UseHangfireServer() to create a Recurring task.
RecurringJob.AddOrUpdate( () => Debug.WriteLine("Minutely Job"), Cron.Minutely);
Run the app and observe Visual Studio output window. “I am a minutely job.” will be written to output window after every minute. And if we take a look at dashboard, all the information related to the job is there.
You can find HangFire documentation on their website.
Summary
HangFire is a great tool and makes life easy for background job processing. And the good thing is that is uses persistence storage for job information. So in case of application failure, information is not lost. If you have not used HangFire yet, it’s worth to give it a try. And integrating this with ASP.NET Core is also quite simple and straight forward.
Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in comments section.
For the demonstration purposes, create a Recurring Task which will write something to output window every minute. So add the following line in Startup.cs -> Configure(), below the app.UseHangfireServer() to create a Recurring task.|
Is it somehow possible to call the function from controller as a hangfire recurring task? If yes, how? Or I should place all my calls inside startup.cs…
Getting a “Could not load type ‘System.Diagnostics.Debug’ from assembly ‘mscorlib'” error with this example under dotnet core 3.0 in the Recurring Jobs tab.
I am using hangfire on my asp.net core web api and angular project. Hangfire is working on localhost but not in production. Also I am not getting the dashboard on Production.
P
I have a console application which contains the logic to invoke an externally hosted web service and gets some data and updates the database. This task needs to executed on weekly basis. Hence I have setup a Task Scheduler to run the console application on weekly basis.
After going through some articles regarding other alternatives available, I came across HangFire.
I am interested to leverage Hangfire as it gives me a good way to use its dashboard to check the status of the jobs that are executed on the background.
Now if I want to use Hangfire to invoke the console application on weekly basis instead of the Task Scheduler, then how to host the console application using Hangfire on the server.
Can anyone guide me here with their inputs.
I never used HangFire to run console application but after some googling I found this link from HangFire docs and I believe this should help you.
http://docs.hangfire.io/en/latest/background-processing/processing-jobs-in-console-app.html