Background jobs in ASP.NET Core: BackgroundService, Hangfire or Quartz, and the IIS trap
Short answer: use a plain BackgroundService for simple loops and queue consumers, Hangfire when business jobs must be persistent, retried and visible in a dashboard, and Quartz.NET when schedules get complicated. Whatever you choose, on IIS the app pool must stay alive (AlwaysRunning, idle timeout 0, preload), or your 2 a.m. job will silently never run.
A real example: the reconciliation that only ran on busy days
A nightly reconciliation job was scheduled for 02:30. Some mornings there was a report, some mornings not. The job had no bug. On quiet nights nobody hit the site after midnight, IIS shut the worker process down after 20 idle minutes, and at 02:30 there was simply no process to run anything. On busy nights a late user kept it alive.
Two settings fixed it. The lesson: in-process jobs are only as reliable as the process that hosts them.
Choosing a runner
| BackgroundService | Hangfire | Quartz.NET | |
|---|---|---|---|
| Extra packages | None | Hangfire + storage | Quartz + optional store |
| Persistent jobs and retries | You build it | Yes (SQL Server) | Yes (with ADO store) |
| Cron schedules | You build it | Yes | Yes, very rich |
| Dashboard | No | Yes | No (third-party) |
| Best for | Simple loops, queue consumers | Business jobs you need to see and retry | Complex calendars and triggers |
BackgroundService: enough for more than you think
public sealed class ExpireHoldsWorker(IServiceScopeFactory scopes, TimeProvider clock,
ILogger<ExpireHoldsWorker> log) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken ct)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
while (await timer.WaitForNextTickAsync(ct))
{
try
{
await using var scope = scopes.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var now = clock.GetUtcNow();
var expired = await db.WalletHolds
.Where(h => h.ExpiresAtUtc < now && h.ReleasedAtUtc == null)
.ExecuteUpdateAsync(s => s.SetProperty(h => h.ReleasedAtUtc, now), ct);
if (expired > 0) log.LogInformation("Released {Count} expired holds", expired);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
log.LogError(ex, "Expire holds run failed"); // never let one failure kill the loop
}
}
}
}
Two habits make it robust: create a scope per run (a DbContext is not a singleton), and catch per iteration so one failure doesn't end the loop for the life of the process.
Hangfire: when jobs must be seen and retried
using Hangfire;
builder.Services.AddHangfire(c => c
.UseSqlServerStorage(builder.Configuration.GetConnectionString("Default")));
builder.Services.AddHangfireServer();
var app = builder.Build();
app.UseHangfireDashboard("/jobs", new DashboardOptions
{
Authorization = [new AdminOnlyDashboardFilter()], // never leave this open
});
app.Services.GetRequiredService<IRecurringJobManager>().AddOrUpdate<ReconciliationJob>(
"nightly-reconciliation",
job => job.RunAsync(CancellationToken.None),
"30 2 * * *",
new RecurringJobOptions { TimeZone = TimeZoneInfo.FindSystemTimeZoneById("Iran Standard Time") });
Jobs survive restarts because they live in SQL Server, failed runs are retried automatically, and the dashboard shows what ran, what failed and why. Protect the dashboard: it can trigger and delete jobs.
The IIS trap
<!-- applicationHost.config, or the equivalent Plesk / IIS Manager settings -->
<applicationPools>
<add name="MyApp" startMode="AlwaysRunning">
<processModel idleTimeout="00:00:00" />
<recycling><periodicRestart time="00:00:00" /></recycling>
</add>
</applicationPools>
<sites>
<site name="MyApp">
<application path="/" applicationPool="MyApp" preloadEnabled="true" />
</site>
</sites>
On Plesk, the same options live under the site's IIS settings (application pool: start mode, idle timeout, recycling) and require the Application Initialization feature on the server. Also schedule an external uptime ping as a safety net. If the server is under your control and jobs are critical, a separate Windows service or worker is even simpler.
Pros and cons
BackgroundService: no dependencies and full control, but no persistence, no retries and no dashboard unless you build them.
Hangfire: persistent jobs, retries and a dashboard out of the box, at the cost of extra tables, a polling load on SQL Server and a dashboard to secure.
Quartz.NET: the richest scheduling (calendars, misfire rules, many triggers), but more configuration and no built-in UI.
Jobs that run "most nights"? See how I can help.
Frequently asked questions
Why didn't my BackgroundService run at night on IIS?
IIS starts the app on the first request and stops the worker process after 20 idle minutes by default, and it also recycles the pool every 29 hours. With no traffic at 2 a.m., there is no process to run the job. Set startMode AlwaysRunning, idle timeout 0 and preloadEnabled, or run jobs in a Windows service.
Is Hangfire free for commercial use?
Hangfire's core is open source (LGPL) and free for commercial use, including SQL Server storage and the dashboard. Hangfire Pro adds features such as batches and Redis storage for a fee. Check the current licence terms for your case.
Can two servers run the same recurring job twice?
A plain BackgroundService on two instances runs twice. Hangfire and Quartz with a shared database store coordinate through locks, so each occurrence runs once. For BackgroundService, use a database lock or run the job on one instance.