Coming from Hangfire
This page maps Hangfire 1.8.25 (tag v1.8.25) to Quartz.NET 4.1. To weigh the two against each other, see Comparison.
The main difference: Hangfire's unit of work is a method call; Quartz's is a type.BackgroundJob.Enqueue(() => mailer.SendWelcome("[email protected]")) serializes an expression tree and replays the call later. Quartz stores a job type and a data map, and the container builds the job for each firing:
// A Hangfire job is a method named by an expression tree; a Quartz job is a type. Its payload is a
// constructor-injected service, a JobDataMap entry, or — as here — the typed input of IJob<TInput>.
public sealed class SendWelcomeEmailJob : IJob<string>
{
private readonly IMailer mailer;
public SendWelcomeEmailJob(IMailer mailer) => this.mailer = mailer;
public ValueTask Execute(IJobExecutionContext context, string emailAddress, CancellationToken cancellationToken = default)
{
return mailer.SendWelcome(emailAddress, cancellationToken);
}
}
A method argument becomes a constructor-injected service, a JobDataMap entry, or the typed input of IJob<TInput>.
From 4.3 a recurring job can also be a lambda, with its services as parameters: q.ScheduleJob("send-digest", (IMailer mailer, CancellationToken ct) => …, t => t.WithCronSchedule(…)). It is stored by its key, not as a serialized call, so every node registers it. See Delegate Jobs.
The API, side by side
Scheduling
| Hangfire | Quartz.NET | Difference |
|---|---|---|
BackgroundJob.Enqueue(() => …) | scheduler.ScheduleJob<TJob, TInput>(input, TimeSpan.Zero) | a trigger that fires now, not a queue entry |
BackgroundJob.Schedule(() => …, TimeSpan) | the same call with the delay | |
BackgroundJob.Schedule(() => …, DateTimeOffset) | the DateTimeOffset overload of the same call | |
BackgroundJob.Delete(jobId) | scheduler.UnscheduleJob(triggerKey) | the TriggerKey on the returned ScheduledOneOffJob is the handle |
BackgroundJob.Requeue(jobId) | scheduler.TriggerJob(jobKey), optionally with a JobDataMap | fires the job again now; there is no failed record to requeue |
BackgroundJob.Reschedule(jobId, …) | scheduler.RescheduleJob(triggerKey, newTrigger) | |
BackgroundJob.ContinueJobWith(parentId, …) | .StartAfter(parentTriggerKey, condition) on the follow-up's trigger | see Continuations |
RecurringJob.AddOrUpdate(id, () => …, cron) | q.AddJob<T>(…) + q.AddTrigger<T>(t => t.WithCronSchedule(…)), or from 4.3 q.ScheduleJob(id, lambda, t => t.WithCronSchedule(…)) | six cron fields, not five, and a different default time zone |
Cron.MinuteInterval(10), Cron.HourInterval(6), Cron.Daily(3, 0) | from 4.3, t.WithCronSchedule(cron => cron.Every(TimeSpan.FromMinutes(10))), cron.Every(TimeSpan.FromHours(6)), cron.AtTime(new TimeOnly(3, 0)) | an interval that does not divide the hour or day throws instead of firing unevenly |
RecurringJob.RemoveIfExists(id) | scheduler.DeleteJob(jobKey), or UnscheduleJob to keep the job | |
RecurringJob.TriggerJob(id) | scheduler.TriggerJob(jobKey) | |
IBackgroundJobClient, IRecurringJobManager | IScheduler, injected | one interface for both; every member is awaitable |
Both ScheduleJob overloads return a ScheduledOneOffJob with the TriggerKey and the first fire time; see One-Off Job for grouping them so a whole conversation can be cancelled at once.
// BackgroundJob.Enqueue(() => mailer.SendWelcome("[email protected]"))
await scheduler.ScheduleJob<SendWelcomeEmailJob, string>(
"[email protected]",
TimeSpan.Zero,
cancellationToken: cancellationToken);
// BackgroundJob.Schedule(() => mailer.SendWelcome("[email protected]"), TimeSpan.FromDays(1))
ScheduledOneOffJob tomorrow = await scheduler.ScheduleJob<SendWelcomeEmailJob, string>(
"[email protected]",
TimeSpan.FromDays(1),
cancellationToken: cancellationToken);
// BackgroundJob.Delete(jobId) — the TriggerKey is the handle, and it is the trigger that goes
await scheduler.UnscheduleJob(tomorrow.TriggerKey, cancellationToken);
A recurring job becomes a durable job plus a trigger, with a new cron format and an explicit time zone:
// RecurringJob.AddOrUpdate("nightly-import", () => importer.Run(), "0 2 * * *")
services.AddQuartz(q =>
{
q.AddJob<NightlyImportJob>(j => j.WithIdentity("nightly-import"));
q.AddTrigger<NightlyImportJob>(t => t
.ForJob("nightly-import")
// Six fields, and one of the two day fields must be '?'. A Hangfire expression is
// five fields read as minutes upward, so prepend the seconds field.
.WithCronSchedule("0 0 2 * * ?", x => x
// Hangfire reads a cron in UTC unless RecurringJobOptions says otherwise; a
// Quartz cron trigger reads it in the machine's local zone unless you say
// otherwise. Say otherwise.
.InTimeZone(TimeZoneInfo.Utc)));
});
Attributes and filters
| Hangfire | Quartz.NET | Difference |
|---|---|---|
[AutomaticRetry(Attempts = n)] | [RetryPolicy(…)] on the job type, or RetryPolicy on a trigger | opt-in: nothing is retried without a policy; see Retry |
[DisableConcurrentExecution(seconds)] | [DisallowConcurrentExecution] | no timeout, because nothing waits; see below |
[Queue("critical")] | an execution group and a limit | bounds concurrency; does not route. See Queues |
[JobDisplayName("…")] | .WithDescription("…") on the job or trigger | |
[LatencyTimeout(seconds)] — delete a job that waited too long to start | the DoNothing misfire instruction | skips that occurrence rather than deleting anything |
GlobalJobFilters.Filters.Add(…) | job execution middleware, or a job listener | middleware wraps the execution; a listener observes it |
PerformContext | IJobExecutionContext | |
context.WriteProgressBar() (Hangfire.Console) | context.ReportProgress(percent, message) | shown on Currently Executing; see Progress and Execution Logs |
context.WriteLine(…) (Hangfire.Console) | an injected ILogger, with q.UseExecutionLogCapture() | the lines go to your logging as well, and onto the execution's history row |
a CancellationToken parameter | the CancellationToken parameter of Execute | same token as IJobExecutionContext.CancellationToken; cancelled by Interrupt and InterruptFireInstance |
Hosting and configuration
| Hangfire | Quartz.NET |
|---|---|
services.AddHangfire(x => x.UseSqlServerStorage(cs)) | builder.AddQuartz(q => q.UsePersistentStore(s => s.UseSqlServer(cs))) |
services.AddHangfireServer() | builder.AddQuartzHostedService() |
BackgroundJobServerOptions.WorkerCount | q.UseDefaultThreadPool(maxConcurrency: n) |
BackgroundJobServerOptions.Queues | — there are no queues; see below |
BackgroundJobServerOptions.ServerTimeout | CheckinInterval and CheckinMisfireThreshold on the clustering options — Tuning the check-in |
SchedulePollingInterval | IdleWaitTime — a ceiling, not a tick: see Sub-minute schedules |
JobStorage.Current.JobExpirationTimeout | ExecutionHistoryOptions.Retention — a different thing; see Retention |
app.UseHangfireDashboard(path, options) | app.MapQuartzDashboard() — will not start without an authorization decision |
IDashboardAuthorizationFilter | RequireAuthorization(policy) at the map site |
DashboardOptions.IsReadOnlyFunc | QuartzDashboardOptions.ReadOnly |
| SQL Server storage creating its own schema | ProvisionSchema(), off by default |
The differences that bite
A cron expression has six fields, and a different default time zone
| Hangfire (Cronos) | Quartz (reference) | |
|---|---|---|
| Fields | five, or six with a leading seconds field | six or seven, seconds first |
| Day fields | * in both | one of the two must be ? (the two are a union) |
| Default time zone | UTC (RecurringJobOptions.TimeZone) | TimeZoneInfo.Local |
- Hangfire's
0 2 * * *is Quartz's0 0 2 * * ?. - Set
InTimeZone(TimeZoneInfo.Utc)on every trigger you move. Otherwise, on a server not in UTC, it fires at a different hour, and twice or not at all on the two days a year the offset changes. CronFormat.Unixkeeps the five-field form. The format is stated, not detected: a five-field string in the default format is an error naming the rewrite.
Sub-minute schedules behave differently
Hangfire enqueues recurring jobs on a poll, BackgroundJobServerOptions.SchedulePollingInterval (fifteen seconds by default), and documents recurring jobs as minute-based. Quartz acquires triggers due within the next IdleWaitTime (thirty seconds by default) and waits for the earliest; a schedule change wakes it early. IdleWaitTime limits idle time, not how soon a trigger fires, so the seconds field is honoured. An expression Hangfire rounded up to a minute fires at its stated cadence in Quartz. See What the loop costs while it waits.
Misfires are decided per trigger, not per job
Hangfire's MisfireHandlingMode is per recurring job. Quartz's misfire instructions are per trigger and differ by trigger kind:
MisfireHandlingMode | The nearest CronTriggerMisfireInstruction |
|---|---|
Relaxed — one job however many occurrences were missed | FireAndProceed — one catch-up, then the schedule resumes |
Strict — one job per missed occurrence | IgnoreMisfires — every missed occurrence, as fast as the pool allows |
Ignorable — none | DoNothing — skips to the next scheduled occurrence |
- Both defaults match: Hangfire's is
Relaxed, and Quartz'sSmartPolicymeansFireAndProceedfor a cron trigger. - "Late" is Hangfire's polling interval, and Quartz's
MisfireThresholdon the job store: one minute for the ADO.NET store, five seconds in memory.
DisableConcurrentExecution waits; [DisallowConcurrentExecution] does not
Hangfire's attribute takes a distributed lock with a timeout; a worker that times out throws DistributedLockTimeoutException, which AutomaticRetry then retries. Quartz's attribute has no timeout: while a firing of the job key runs, its other triggers are Blocked and released on completion, with no worker occupied. With a persistent store the exclusion is cluster-wide.
From 4.3 a trigger can decide instead of its job, with an overlap policy: BufferOne holds one firing until the running one ends, Skip drops it, CancelPrevious interrupts the running one.
Queues become limits, not routes
Hangfire's [Queue] bounds how much work runs and chooses which servers run it (a server subscribes to queue names). Quartz's execution groups only bound:
// [Queue("reports")] on the job, plus a server that subscribes to that queue
services.AddQuartz(q =>
{
q.AddJob<ReportingJob>(j => j.WithIdentity("monthly-report"));
q.AddTrigger<ReportingJob>(t => t
.ForJob("monthly-report")
.WithCronSchedule("0 0 3 1 * ?")
.WithExecutionGroup("reports"));
q.UseExecutionLimits(limits =>
{
// Two at a time across every node sharing the store, rather than two per process.
limits.ForGroup("reports", maxConcurrent: 2, ExecutionLimitScope.Cluster);
});
});
ExecutionLimitScope.Clustercounts the limit across the cluster (Hangfire's equivalent isHangfire.Throttling, on the Business tier).- There is no routing. To run on particular machines, pin a trigger to an instance with
PreferredNode, or use a second scheduler with its own store.
Retry is opt-in
Hangfire's AutomaticRetryAttribute is in GlobalJobFilters by default: every job retries ten times. Quartz retries only when a policy applies: the trigger's own, the job type's [RetryPolicy], or the scheduler's default. The attribute is the counterpart of [AutomaticRetry]:
// [AutomaticRetry(Attempts = 3, DelaysInSeconds = new[] { 60, 300, 900 })]
[RetryPolicy("00:01:00", "00:05:00", "00:15:00")]
public sealed class NightlyImportJob : IJob
{
public ValueTask Execute(IJobExecutionContext context, CancellationToken cancellationToken = default) => default;
}
UseDefaultRetryPolicy is the counterpart of the global filter:
// GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 10 })
services.AddQuartz(q =>
{
// Every trigger whose own policy and job type name none.
q.UseDefaultRetryPolicy(RetryPolicy.Exponential(
maxAttempts: 10,
initialDelay: TimeSpan.FromSeconds(15),
factor: 2,
maxDelay: TimeSpan.FromHours(1),
jitter: 0.2));
});
- A trigger's own policy beats the job type's, so two triggers of one job can retry differently.
- A scheduled retry is stored with the trigger, so it survives a restart and any node runs it.
- Waits are exact unless
Exponentialis given jitter (its fifth argument), which spreads them as Hangfire's do. - A retry never displaces the trigger's next occurrence, running out is not an error, and a retry uses no repeat count. When attempts run out,
ITriggerListener.TriggerRetriesExhausted, a log event, a counter and a final history row report it; the row has the dashboard's Run again button, the equivalent of a requeue. From 4.4 it passes the run's input back when the history records inputs. See When the policy gives up. - From 4.3,
PauseTriggerWhenRetriesExhausted()pauses a trigger that gave up, with the error as the reason, so it stays stopped until resumed, as a Hangfire job staysFaileduntil requeued.
Continuations
ContinueJobWith (a JobContinuationOptions, default OnlyOnSucceededState) becomes a continuation: a trigger with StartAfter(parentTriggerKey, condition), held by the store in TriggerState.Awaiting and released inside the parent's transaction. OnSuccess is the default.
- The parent is a trigger firing, not a job. Use the
TriggerKeythe one-call overloads return; for a job with several triggers, name the one to wait for. - The conditions differ.
OnSuccess,OnFailure,OnCancellationandOnVetoare flags (OnFailure | OnCancellationneeds no member). Nothing matchesOnlyOnDeletedState: Quartz keeps no job record to delete. - For a recurring conditional chain, use
JobChainingJobListenerwith the same conditions. Its links fire on every completion but live in memory: re-registered on every start, and the follow-up runs on the node that ran the parent.
Job expiration is not history retention
Hangfire's JobStorage.Current.JobExpirationTimeout keeps succeeded and deleted job records for one day; failed ones never expire and stay in the dashboard. Quartz keeps no job record: a firing's fired-trigger row is deleted when it completes. What remains is the execution history, in memory by default, 2,000 entries per scheduler for 24 hours (ExecutionHistoryOptions.Retention, MaxEntriesPerScheduler). It is a recent-activity view; keep durable records in your logging pipeline.
The dashboard is fail-closed
Hangfire's dashboard is readable from localhost by default. Quartz's stops the application from starting until the mapping says RequireAuthorization, or AllowAnonymous if you mean it:
// app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = [ ... ] })
app.MapQuartzDashboard().RequireAuthorization("QuartzOperators");
See Production hardening for read-only mode and the job type allow-list.
What "once" means
Hangfire retries a job interrupted by an exception or shut-down, so it asks for re-entrant methods. In Quartz a firing lost with its node is not repeated unless the job asks for recovery with RequestRecovery(). Write jobs to be safely re-run either way; see Best Practices.
Running both while you move
They are separate hosted services on separate schemas, so they can share a host. A recurring job registered in both runs twice, unreported: remove each schedule from Hangfire before adding it to Quartz.
See also
- Comparison — the two weighed against each other, sourced
- One-Off Job — the
ScheduleJob<TJob, TInput>overloads in full - Retrying Failed Jobs — the retry policy and its rules
- Execution Groups — what
[Queue]becomes - Migration Guide — for a move from Quartz 3.x rather than from Hangfire
