With Hangfire, what is the difference between BackgroundJob.Enqueue, BackgroundJob.Schedule and RecurringJob.AddOrUpdate, and when do you use each?
answer
- three job kinds plus continuations
- Enqueue returns the job id string
- Schedule takes TimeSpan or DateTimeOffset
- AddOrUpdate stores a definition, not a job
- Cron.Daily() means midnight UTC
basics
~20 sBackgroundJob.Enqueue creates a fire-and-forget job that runs as soon as a worker is free; BackgroundJob.Schedule creates a job that runs after a delay or at a set time; RecurringJob.AddOrUpdate registers a cron schedule that creates a new job at every occurrence.
solid answer
~40 sAll three write to Hangfire's storage and return at once, so the request never runs the work itself. `BackgroundJob.Enqueue(() => ...)` creates a **fire-and-forget** job in the Enqueued state and returns its id as a `string`; a worker on any Hangfire server listening to its queue picks it up. `BackgroundJob.Schedule(() => ..., TimeSpan.FromHours(1))` (or a `DateTimeOffset`) creates a **delayed** job in the Scheduled state, which the server's scheduler moves to the queue once the time has passed: the shop's abandoned-cart reminder an hour after a cart goes idle. `RecurringJob.AddOrUpdate("nightly-sales-report", () => ..., Cron.Daily(2))` creates no job at all: it stores a **recurring job** definition, an id plus a cron expression, and each occurrence creates a fresh background job. The fourth kind, `BackgroundJob.ContinueJobWith(parentId, ...)`, waits for a parent job to finish.
code
csharp · 20 lines// Program.cs (Hangfire 1.8, after AddHangfire and AddHangfireServer)
using Hangfire;
app.MapPost("/orders/{orderId:int}/confirm", (int orderId, IBackgroundJobClient jobs) =>
{
// fire-and-forget: a worker sends the e-mail
var jobId = jobs.Enqueue<IOrderMailer>(m => m.SendConfirmationAsync(orderId));
return Results.Accepted(value: new { jobId });
});
app.MapPost("/carts/{cartId:guid}/idle", (Guid cartId, IBackgroundJobClient jobs) =>
{
// delayed: remind the shopper in one hour
jobs.Schedule<ICartReminder>(r => r.RemindAsync(cartId), TimeSpan.FromHours(1));
return Results.NoContent();
});
// recurring: one stored definition, a new job every night at 02:00 UTC
app.Services.GetRequiredService<IRecurringJobManager>()
.AddOrUpdate<ISalesReportService>("nightly-sales-report", s => s.BuildAsync(), Cron.Daily(2));go deeper
Name the three kinds and the call for each: Enqueue for now, Schedule for later, AddOrUpdate with an id and a cron for repeating work, and say that each returns before the work runs.
Explain that every call only writes a record to storage, that Schedule depends on a polling scheduler, and that a recurring job is a definition which spawns ordinary jobs.
Show how you pick between them for real flows: cancellable delayed jobs that still guard themselves, recurring definitions registered idempotently, and when a hosted service is the simpler tool.
Frame Hangfire as durable, storage-backed work distribution, and weigh its operational cost against in-process loops or a message broker for the shop's workload.
## What a Hangfire job is A **Hangfire background job** is a method call recorded in persistent storage (SQL Server, PostgreSQL, Redis and others): the type, the method, its parameter types and its serialized arguments. The **client** side writes that record; in ASP.NET Core it is the static `BackgroundJob` / `RecurringJob` classes or the injected `IBackgroundJobClient` / `IRecurringJobManager`. The **server** side, added with `AddHangfireServer`, runs workers that fetch jobs from storage and invoke the method. Because the job is stored before anything runs, it survives an application restart, a deploy or a crash, and it can run on a different machine from the one that created it. That is the point of using Hangfire instead of `Task.Run` or an unawaited task inside an endpoint, whose work lives only in one process's memory. ## The four ways to create work | API | Kind | State it is created in | When the method runs | Returns | |---|---|---|---|---| | `BackgroundJob.Enqueue` | fire-and-forget | Enqueued | as soon as a worker is free | the job id (`string`) | | `BackgroundJob.Schedule` | delayed | Scheduled | after a `TimeSpan`, or at a `DateTimeOffset` | the job id | | `BackgroundJob.ContinueJobWith` | continuation | Awaiting | after a parent job finishes | the job id | | `RecurringJob.AddOrUpdate` | recurring | none: it stores a definition | each cron occurrence creates a new job | `void` | The lambda you pass is an **expression tree**, not a delegate Hangfire calls later: Hangfire reads which method it names and evaluates the arguments right away. ## Fire-and-forget: `Enqueue` Use it when the caller should not wait for slow or unreliable work: sending the order-confirmation e-mail after checkout, resizing product images, calling a payment provider's slow reconciliation API. The endpoint returns as soon as the job row is written, and the returned id can be logged or stored to look the job up later. ## Delayed: `Schedule` Use it when the work belongs to a moment relative to an event. In an online shop the classic case is the **abandoned-cart reminder**: when a cart goes idle, schedule a reminder for one hour later. Two details matter: - The time is a lower bound, not an appointment. A server-side scheduler checks for due jobs on a polling interval (`BackgroundJobServerOptions.SchedulePollingInterval`, 15 seconds by default) and then enqueues them, where they wait for a free worker. - You can cancel it. Keep the id `Schedule` returned and call `BackgroundJob.Delete(jobId)` when the customer checks out first. The reminder job itself should still re-check the cart when it runs, because the delete can race with a worker that has just picked the job up. ## Recurring: `AddOrUpdate` Use it for calendar-driven work: the **nightly sales report**, a weekly stock-level export, an hourly cache warm-up. `RecurringJob.AddOrUpdate` stores a definition under an id you choose, with a cron expression such as `Cron.Daily(2)` (the string `"0 2 * * *"`). It does not run anything when called; each time the cron fires, the recurring-job scheduler creates an ordinary background job from the definition, and that job is processed, retried and listed like any other. In Hangfire 1.8 every overload without an explicit recurring job id is `[Obsolete]`, and the schedule is read in UTC unless `RecurringJobOptions.TimeZone` says otherwise. ## Choosing between them 1. The user must not wait, and the work must not be lost: `Enqueue`. 2. The work belongs to a later moment tied to one event: `Schedule`, keeping the id if it may need cancelling. 3. The work belongs to the calendar, not to an event: a recurring job. 4. The work must follow another job: `ContinueJobWith`. 5. The loop is in-process, needs no persistence and no dashboard: a plain hosted service, not Hangfire at all. What ties all four together is that the caller only **creates** a record; the decision of when and where the method runs belongs to the Hangfire servers reading the same storage.
- Why not just call Task.Run from the endpoint instead of BackgroundJob.Enqueue?Work started with `Task.Run` exists only in that process's memory: a restart, a deploy or a crash loses it, nothing retries it, and no other instance can pick it up. `Enqueue` writes the job to storage first, so it survives restarts, can run on any Hangfire server, and is retried and visible like every other job.
- How do you cancel the abandoned-cart reminder if the customer checks out within the hour?Store the id that `Schedule` returned, for example on the cart row, and call `BackgroundJob.Delete(jobId)` (or `IBackgroundJobClient.Delete`) at checkout; it moves the job to Deleted and returns whether the state change happened. Keep a guard in the job too, re-reading the cart and exiting if it was checked out, because a worker may already have started it.
- BackgroundJob.Enqueue runs the lambda straight away on the thread pool, like Task.Run.
- A fire-and-forget Hangfire job is lost if the app restarts before it runs.
- BackgroundJob.Schedule fires at exactly the second you asked for.
- RecurringJob.AddOrUpdate runs the job once immediately and then on the schedule.
- Cron.Daily() runs at midnight in the server's local time zone.