Member-only story
Schedule Background Jobs Using Hangfire in .NET Core

You might have found a variety of use cases of background tasks or scheduled jobs in application development. For example, we can delegate long running tasks to background threads. Most importantly, we sometimes need to schedule background jobs to keep domain models in consistent states, especially when the model state is mutated due to a time-triggered event.
This post is neither to discuss the differences between Hangfire and native .Net Core IHostedService
(read more at my another blog post), nor to discuss the pros/cons of all background job schedulers on the market. I simply want to summarize the integration of Hangfire and .NET Core.
Table of Contents
- 1. Install Hangfire NuGet Package
- 2. Define and Implement a Background Job
- 3. Arrange Job Scheduler for Recurring Jobs
- 4. Add Hangfire into .NET Core Service Collection
- 5. Set up Hangfire Dashboard
1. Install Hangfire NuGet Package
As of the time of writing, the current stable version of Hangfire is 1.6.22. Hangfire v1.7.0 is comming soon.
Once we have created a .NET Core web project (or other project types that allow us to inject dependencies and/or do authentications), we can install the Hangfire NuGet package through Visual Studio NuGet Package Manager, or install the package via command line tools.
dotnet add package Hangfire
The Hangfire NuGet package includes Hangfire.Core
and Hangire.SqlServer
. If you are using another Database Provider, then you need to install the corresponding NuGet package. Here, I use SqlServer for my example.
Once the NuGet package is installed, we will have a copy of SQL migration script located at C:\Users\{windows user name}\.nuget\packages\hangfire.sqlserver\1.6.22\tools
folder. The SQL script is well written and designed, so that when we update our Hangfire version, we can confidently run the new script included in the package to update the SQL database schema.
Please run the SQL script before you proceed. If you are using a newer version of Hangfire, then run the SQL script in your…