This article looks at setting up Hangfire with ASP.NET Core and an SQL server. Hangfire provides a solution to run recurring jobs and background jobs with an excellent dashboard to monitor the events.
Code: https://github.com/damienbod/AspNetCoreHangfire
The ASP.NET Core application uses two Hangfire Nuget packages to integrate the event handling into the solution.
- Hangfire.AspNetCore
- Hangfire.SqlServer
The program file initializes the services and adds the middleware to the project. The SQL Server is setup using the extension methods from the Hangfire Nuget packages and uses a connection string from the app settings in development.
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var configuration = builder.Configuration;
var env = builder.Environment;
services.AddHangfire(hangfire =>
{
hangfire.SetDataCompatibilityLevel(CompatibilityLevel.Version_170);
hangfire.UseSimpleAssemblyNameTypeSerializer();
hangfire.UseRecommendedSerializerSettings();
hangfire.UseColouredConsoleLogProvider();
hangfire.UseSqlServerStorage(
configuration.GetConnectionString("HangfireConn"),
new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
});
var server = new BackgroundJobServer(new BackgroundJobServerOptions
{
ServerName = "hangfire-test",
});
});
// other services...
var app = builder.Build();
app.UseHangfireDashboard();
// more middleware...
app.Run();
}
SQL database setup
The SQL database is setup using the Hangfire documentation.
https://docs.hangfire.io/en/latest/configuration/using-sql-server.html
The hangfire script can be found in the hangfire repository. I also added a copy of this script in the demo repository: hangfire-default-install.sql
Create a recurring job
Now that Hangfire is setup, jobs can be created. I use a class to implement the method called after a Hangfire event has been fired. The method must be reentrant and needs to handle the exceptions.
public class MyRecurringJob : IMyRecurringJob
{
public void DoSomethingReentrant()
{
Console.WriteLine("IMyRecurringJob doing something");
}
}
The job can be created using the RecurringJob.AddOrUpdate method. This adds the job to the SQL database.
RecurringJob.AddOrUpdate<IMyRecurringJob>(
job => job.DoSomethingReentrant(), Cron.Hourly);
Create a background job
A Hnagfire background job can be created using the BackgroundJob.Enqueue method. The methods have various parameters which can be used anc covers most of the event, job requirements which can exist.
BackgroundJob.Enqueue<IMyBackgroundJob>(x => x.DoSomethingReentrant());
Delete background jobs
Deleting the jobs is required if you deploy regularly as different instances are created and new recurring jobs are created then. The following code makes it possible to delete the recurring jonbs.
using (var connection = JobStorage.Current.GetConnection())
{
foreach (var recurringJob in connection.GetRecurringJobs())
{
RecurringJob.RemoveIfExists(recurringJob.Id);
}
}
Running the applications
When the applications are created and different jobs can be created or deleted.

Hangfire Dashboard
Hangfire provides an excellent dashboard which can display the running or failed jobs and the different server setups.

Notes
This is just the basic setup of Hangfire. You can integrate Hangfire in various ways into a solution, but KISS should always be followed. Using events inside solutions is already complicated and requires extra tools to monitor and debug. You should also only use this if the business logic requires this. To use Hangfire inside a professional solution, you would need to add security to the dashboard, probably inject services inside the code that executes the jobs which has problems, add logging and the executing code must be reentrant due to retries.
Hangfire is a great tool as with many other tools, solutions for this type of problem. The jobs need to be reentrant. For long running workflows which require persistence, maybe other tools would be the better choice, for example Azure durable functions or power automate. Background services also work really good for simple jobs. ASP.NET Core Quartz can also be used. All these tools are very good and you should try to choose the one which best fits your needs and follows the KISS principal.
Links
https://docs.hangfire.io/en/latest/getting-started/aspnet-core-applications.html
https://jonhilton.net/simple-background-jobs-with-hangfire-and-aspnet-core/