Lesson 5 of 8
Hangfire - Persistent Job Scheduling
Unlike BackgroundService+Channel (in-process, jobs lost on app restart), Hangfire persists jobs in a database. Jobs survive restarts, can be retried on failure, and scheduled for specific times. The Hangfire Dashboard provides a Web UI to monitor and manage all jobs.
Hangfire Setup - Fire & Forget, Delayed, Recurring
// dotnet add package Hangfire.AspNetCore
// dotnet add package Hangfire.SqlServer (or .PostgreSql)
using Hangfire;
// ━━ Registration ━━
builder.Services.AddHangfire(config =>
config.SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(builder.Configuration.GetConnectionString("DefaultConnection"),
new Hangfire.SqlServer.SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero, // instant delivery
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
UseRecommendedIsolationLevel = true,
}));
builder.Services.AddHangfireServer(options =>
{
options.WorkerCount = Environment.ProcessorCount * 2;
options.Queues = ["critical", "default", "low"]; // priority queues
});
// In pipeline:
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = [new HangfireAuthorizationFilter()], // protect dashboard!
AppPath = "/"
});
// ━━ Job types ━━
// 1. Fire and forget - run once ASAP, auto-retry on failure
BackgroundJob.Enqueue<IEmailService>(email =>
email.SendAsync("user@example.com", "Order Confirmed", "<p>Your order was placed!</p>", default));
// 2. Delayed - run at a specific time in the future
BackgroundJob.Schedule<IOrderService>(order =>
order.SendReminderAsync(orderId, default),
TimeSpan.FromDays(3));
// 3. Recurring jobs - cron schedule
RecurringJob.AddOrUpdate<IReportService>(
recurringJobId: "daily-sales-report",
methodCall: report => report.GenerateDailySalesReportAsync(default),
cronExpression: Cron.Daily(hour: 6)); // every day at 6am UTC
RecurringJob.AddOrUpdate<IInventoryService>(
"inventory-sync",
inv => inv.SyncFromWmsAsync(default),
Cron.Hourly());
// 4. Continuations - run after another job completes
var processingJobId = BackgroundJob.Enqueue<IOrderService>(o =>
o.ProcessPaymentAsync(orderId, default));
BackgroundJob.ContinueJobWith<IFulfillmentService>(processingJobId, f =>
f.FulfillOrderAsync(orderId, default)); // runs only if ProcessPayment succeeded
// ━━ Dashboard auth (only Admins can access) ━━
public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
var httpContext = context.GetHttpContext();
return httpContext.User.IsInRole("Admin");
}
}
interface IEmailService { Task SendAsync(string to, string subject, string body, System.Threading.CancellationToken ct); }
interface IOrderService { Task SendReminderAsync(System.Guid id, System.Threading.CancellationToken ct); Task ProcessPaymentAsync(System.Guid id, System.Threading.CancellationToken ct); }
interface IReportService { Task GenerateDailySalesReportAsync(System.Threading.CancellationToken ct); }
interface IInventoryService { Task SyncFromWmsAsync(System.Threading.CancellationToken ct); }
interface IFulfillmentService { Task FulfillOrderAsync(System.Guid id, System.Threading.CancellationToken ct); }
System.Guid orderId = System.Guid.NewGuid();Tip
Tip
Practice Hangfire Persistent Job Scheduling in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Hangfire Persistent Job Scheduling from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Hangfire Persistent Job Scheduling is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?