Recipe 14.6 · C#
When to Reach for Quartz.NET or Hangfire
Problem
The schedule list grows: billing at 2:00 on weekdays, a report at 6:00 on the first business day of the month, an archive job every Sunday. Jobs must not run twice when the service runs on two servers. Operations want to see what ran, what failed, and to rerun a failed job without a deployment. The hosted services from this chapter can do some of this, but you would be writing a scheduler.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: a hand-written scheduler that grew a table and a parser
if (job.Frequency == "Daily" && now.Hour == job.Hour) Run(job);
else if (job.Frequency == "Weekly" && now.DayOfWeek == job.Day) Run(job);
else if (job.Frequency == "Monthly" && now.Day == job.DayOfMonth) Run(job);
// ...plus a ScheduledJob table, a LastRun column and a lock flag
I have inherited more than one of these: a JobScheduler class, a ScheduledJobs
table, and years of patches for daylight saving time, months with 30 days and locks that were never
released after a crash.
The improved recipe
Use a library once the requirements pass a simple interval or a single daily time. This table is how I decide:
| Requirement | Reach for |
|---|---|
| Fixed interval, one instance | TimedJobService (14.1) |
| One time of day | DailyJobService (14.2) |
| Fire-and-forget, loss is acceptable | Channels (14.4) |
| Cron schedules, calendars, clustering | Quartz.NET |
| Durable queued jobs, retries, dashboard | Hangfire |
Quartz.NET 3.x, from the Quartz.Extensions.Hosting package, runs cron-style schedules in the
Generic Host. (Quartz.NET 4 targets .NET 10 and moves these APIs into the main Quartz package.) A small adapter lets the IScheduledJob classes from this chapter run under Quartz without
changes:
using System;
using System.Threading.Tasks;
using Quartz;
namespace ImproveCode.Jobs;
[DisallowConcurrentExecution]
public sealed class QuartzJobAdapter<TJob>(TJob job) : IJob
where TJob : class, IScheduledJob
{
public Task Execute(IJobExecutionContext context) =>
job.RunAsync(context.CancellationToken);
}
public static class QuartzConfiguratorExtensions
{
public static IServiceCollectionQuartzConfigurator AddCronJob<TJob>(
this IServiceCollectionQuartzConfigurator quartz,
string cronExpression,
TimeZoneInfo zone)
where TJob : class, IScheduledJob
{
var key = new JobKey(typeof(TJob).Name);
quartz.AddJob<QuartzJobAdapter<TJob>>(o => o.WithIdentity(key));
quartz.AddTrigger(t => t
.ForJob(key)
.WithIdentity(key.Name + "-trigger")
.WithCronSchedule(cronExpression, cron => cron
.InTimeZone(zone)
.WithMisfireHandlingInstructionFireAndProceed()));
return quartz;
}
}
using System;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
namespace ImproveCode.Jobs;
public static class SchedulingSetup
{
public static IServiceCollection AddScheduledJobs(
this IServiceCollection services, TimeZoneInfo zone)
{
services.AddScoped<InvoiceSyncJob>();
services.AddQuartz(quartz =>
{
// Seconds, minutes, hours, day of month, month, weekday.
quartz.AddCronJob<InvoiceSyncJob>("0 0 2 ? * MON-FRI", zone);
});
services.AddQuartzHostedService(options =>
{
options.WaitForJobsToComplete = true;
});
return services;
}
}
Hangfire, from the Hangfire.AspNetCore and Hangfire.SqlServer packages, stores every job in
the database, so jobs survive restarts and failures are retried automatically:
using System;
using System.Threading;
using Hangfire;
using Microsoft.Extensions.DependencyInjection;
namespace ImproveCode.Jobs;
public static class HangfireSetup
{
public static IServiceCollection AddDurableJobs(
this IServiceCollection services, string connectionString)
{
services.AddScoped<InvoiceSyncJob>();
services.AddHangfire(config => config
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(connectionString));
services.AddHangfireServer();
return services;
}
public static void RegisterRecurringJobs(
IRecurringJobManager jobs, TimeZoneInfo zone)
{
jobs.AddOrUpdate<InvoiceSyncJob>(
"invoice-sync",
job => job.RunAsync(CancellationToken.None),
"0 2 * * 1-5",
new RecurringJobOptions { TimeZone = zone });
}
public static string EnqueueSync(IBackgroundJobClient client) =>
client.Enqueue<InvoiceSyncJob>(
job => job.RunAsync(CancellationToken.None));
}
How it works
Quartz.NET is a scheduler. Its cron expressions have a seconds field, so 0 0 2 ? * MON-FRI is
2:00:00 on weekdays, and InTimeZone evaluates them in the business time zone with the
daylight-saving handling built in. [DisallowConcurrentExecution] stops a slow run from
overlapping the next one. The misfire instruction says what to do with a run that was missed
while the service was down: fire once now and continue. WaitForJobsToComplete makes Quartz
take part in graceful shutdown. By default Quartz keeps its schedule in memory. Switch to its
ADO.NET job store with clustering enabled and several servers share the schedule, with each run
executed by exactly one of them. Without a clustered scheduler, two servers running the same
hosted service run every job twice; sp_getapplock in SQL Server is the lightweight guard.
The adapter is the reusable part. Jobs stay plain IScheduledJob classes, testable on their own,
and the decision between TimedJobService and Quartz becomes one line of registration.
Hangfire is a durable job queue with a scheduler on top. Enqueue writes the job to SQL Server and
returns at once, and any server running AddHangfireServer picks it up. Failed jobs are retried
with increasing delays, ten times by default. Recurring jobs use standard five-field cron. The
CancellationToken.None in the expression is a placeholder: Hangfire replaces it with a token that
is cancelled at shutdown. Its dashboard, mapped with app.UseHangfireDashboard() in ASP.NET Core,
shows queued, running, failed and succeeded jobs, and lets an operator retry one with a click.
Variations and pitfalls
- Hangfire serializes the call, not the object. The expression is stored as the type, method and arguments. Pass IDs, not entities, and keep job method signatures stable, or queued jobs fail after a deployment that changed them.
- Secure the dashboard. By default it is only available to local requests. Before exposing it,
add an
IDashboardAuthorizationFilterthat checks your application's roles. - Licensing. Quartz.NET is Apache 2.0. Hangfire's core is LGPL with a commercial Pro edition for features such as batches.
- Keep the job code independent. Whichever you choose, the job classes should not reference Quartz or Hangfire types. Then changing schedulers later is a registration change, not a rewrite.