Hangfire is an open-source library for background job processing in .NET applications. It lets you run tasks asynchronously—for example, sending emails, processing images, or performing any lengthy operation—without blocking the main request thread. By handling job persistence, retries, and scheduling, Hangfire keeps your application responsive while ensuring critical background tasks are executed reliably.
Hangfire supports several types of jobs.
- Fire-and-Forget Jobs: Executed only once immediately after creation.
- Delayed Jobs: Scheduled to run after a specified delay.
- Recurring Jobs: Run according to a defined schedule (e.g., every day at a particular time).
- Continuation Jobs: Triggered when their parent job completes.
Prerequisites
Before you begin, ensure you have,
- .NET 8 SDK installed.
- A code editor (Visual Studio or VS Code).
- SQL Server or LocalDB for job storage.
- Basic knowledge of C# and ASP.NET Core.
Setting Up the Sample Project
1. Create a New Minimal API Project
Open your terminal.
dotnet new web -n HangfireSample
2. Add Hangfire NuGet Packages
Navigate to your project folder and run.
cd HangfireSample
dotnet add package Hangfire.AspNetCore
dotnet add package Hangfire.SqlServer
dotnet add Microsoft.Data.SqlClient
3. Configure the Database
Update appsettings.json with your connection string. For example, using LocalDB.
{
"ConnectionStrings": {
"HangfireConnection": "Server=Instance;Database=Your_DB;Integrated Security=True;TrustServerCertificate=true;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
Hangfire will automatically create the necessary tables.
Implementing Hangfire in .NET 8
Replace the contents of Program.cs with the following code.
using Hangfire;
using Hangfire.SqlServer;
var builder = WebApplication.CreateBuilder(args);
// Configure Hangfire to use SQL Server storage.
builder.Services.AddHangfire(config =>
{
config.UseSqlServerStorage(builder.Configuration.GetConnectionString("HangfireConnection"));
});
// Start the Hangfire Server to process background jobs.
builder.Services.AddHangfireServer();
// (Optional) Add Swagger for API testing.
builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();
// Use Swagger UI in development mode.
// Expose the Hangfire Dashboard at /hangfire (be sure to secure this in production).
app.UseHangfireDashboard();
// Root endpoint to test basic connectivity.
app.MapGet("/", () => "Hello World from .NET 8 and Hangfire!");
// Endpoint to enqueue a fire-and-forget job.
app.MapGet("/enqueue", (IBackgroundJobClient backgroundJobs) =>
{
backgroundJobs.Enqueue(() => Console.WriteLine("Hangfire Fire-and-Forget Job executed!"));
return Results.Ok("Background job has been enqueued.");
});
// New endpoint to schedule a delayed job (executes after 1 minute).
app.MapGet("/schedule", (IBackgroundJobClient backgroundJobs) =>
{
backgroundJobs.Schedule(
() => Console.WriteLine("Delayed Hangfire Job executed after 1 minute!"),
TimeSpan.FromMinutes(1)
);
return Results.Ok("Delayed job scheduled to run after 1 minute.");
});
// Run the application.
app.Run();
How does This Work?
Hangfire Configuration
- AddHangfire registers Hangfire with SQL Server storage using the provided connection string.
- AddHangfireServer starts a background server to process the queued jobs.
Endpoints
- Root ("/"): Returns a basic welcome message.
- Enqueue ("/enqueue"): Uses BackgroundJob.Enqueue to immediately queue a fire-and-forget job.
- Schedule ("/schedule"): Uses BackgroundJob.Schedule to queue a job that will execute after a 1-minute delay.
- Hangfire Dashboard: Accessible at /hangfire, it provides real-time monitoring of job statuses (enqueued, processing, succeeded, or failed).
Visual Overview
Architecture Diagram
+-----------------------------+
| Client |
| (Browser, Postman, etc.) |
+--------------+-------------+
|
HTTP Request
|
v
+-----------------------------+
| .NET 8 Minimal API |
| Endpoints: |
| "/" -> Hello World|
| "/enqueue" -> Enqueue |
| "/schedule" -> Delay |
+--------------+-------------+
|
Enqueue / Schedule Command
|
v
+-----------------------------+
| Hangfire Storage (SQL DB) |
+--------------+-------------+
|
Hangfire Server Polls
|
v
+-----------------------------+
| Hangfire Background Job |
| Processor |
+-----------------------------+
Step-by-Step Flow
- Client Interaction: A client calls /enqueues, or /schedules to add jobs.
- Job Storage: Hangfire persists the job details in SQL Server.
- Job Processing: The Hangfire server continuously polls the queue and executes ready jobs.
- Dashboard Monitoring: The Hangfire Dashboard lets you view job states and monitor execution.
Key Terms Explained
- Fire-and-Forget Job (Enqueue): Enqueued tasks that run as soon as they’re picked up. Ideal for operations that don't require an immediate response.
- Delayed Job (Schedule): Tasks that start after a delay—useful for follow-up operations like sending reminders.
- Background Job: Any task executed asynchronously outside the main HTTP request/response cycle.
- Hangfire Server: A service that retrieves and executes background jobs from storage.
- Hangfire Dashboard: A web-based UI for monitoring job statuses. For production, secure this dashboard with proper authentication.
Running and Testing
Start the Application
dotnet run
Test the Endpoints
- Root: Navigate to http://localhost:5000/ to see "Hello World from .NET 8 and Hangfire!"
- Enqueue: Visit http://localhost:5000/enqueue to dispatch a fire-and-forget job.
- Schedule: Visit http://localhost:5000/schedule to schedule a job for execution after one minute.
- Dashboard: Open http://localhost:5000/hangfire to monitor jobs in real time.
Output Samples
![Output Samples]()
Conclusion
This guide demonstrated how to integrate Hangfire into a .NET 8 Minimal API project, covering both immediate (enqueue) and delayed (schedule) job processing. By offloading long-running tasks to background jobs, you can keep your application responsive and scalable.
Next, consider exploring recurring jobs, job continuations, or integrating custom error handling to enrich your background processing capabilities.
Happy coding!