skip to content

With Hangfire 1.8, why does RecurringJob.AddOrUpdate take an explicit recurring job id, and what happens when it runs at every startup?

level: middleimportance: should knowfreq 45%

answer

  1. an upsert, not an append
  2. id-less overloads are [Obsolete]
  3. old implicit id was Type.Method
  4. RemoveIfExists for a retired schedule
  5. TriggerJob creates a run now

basics

~20 s

The id is the recurring job's key in storage: AddOrUpdate creates or overwrites the definition with that id, so calling it at every startup never duplicates it. Hangfire 1.8's id-less overloads, which derived the id from type and method, are obsolete.

solid answer

~40 s

`RecurringJob.AddOrUpdate("nightly-sales-report", () => ..., Cron.Daily(2))`, or the same call on an injected `IRecurringJobManager`, is an **upsert** keyed by that id: under a distributed lock it loads or creates the definition, rewrites the job, and recomputes the next run only if the cron or time zone changed. That is why registering recurring jobs in `Program.cs` on every start, on every instance, is safe. The obsolete id-less overloads used `TypeName.MethodName` as the id, so two schedules for the same method silently overwrote each other and renaming the method left the old definition behind. The id also drives the rest of the lifecycle: `RemoveIfExists(id)` deletes a schedule, which deleting the line of code does **not** do, and `TriggerJob(id)` creates a run immediately. An invalid cron throws `ArgumentException` at registration.

code

csharp · 13 lines
csharp
// Program.cs: Hangfire 1.8 registers recurring jobs idempotently at startup
var app = builder.Build();

var recurring = app.Services.GetRequiredService<IRecurringJobManager>();

recurring.AddOrUpdate<ISalesReportService>(
    "nightly-sales-report",                 // stable id: the key in storage
    s => s.BuildAsync(CancellationToken.None),
    Cron.Daily(2));                          // "0 2 * * *", UTC unless options say otherwise

recurring.RemoveIfExists("hourly-stock-sync"); // retired: deleting the old line is not enough

app.Run();

go deeper

for a junior

Remember to give every recurring job a constant id string and that AddOrUpdate both creates and updates the schedule.

for a middle

Explain the upsert: validation, a lock on the id, rescheduling only when cron or time zone change, and why the id-less overloads collided.

for a senior

Show the operational side: retiring schedules with RemoveIfExists, triggering a run on demand, and registering from every instance without duplicates or races.

for a principal

Treat recurring job ids as part of the system's stored configuration, owned and versioned like database migrations across environments.

## A recurring job is a stored definition A Hangfire **recurring job** is not a job. It is a record in storage, keyed by a **recurring job id**, that holds the method to call, a **cron expression**, a time zone and a misfire policy. The recurring-job scheduler running on the Hangfire servers reads these records and, at each occurrence, creates an ordinary background job from one. Removing, renaming or changing a schedule therefore means changing that record, and the id is how you address it. ## What `AddOrUpdate` does, step by step Reading `RecurringJobManager.AddOrUpdate` in Hangfire 1.8.25: 1. It validates the cron string: five fields, six with seconds, or an `@` macro. Anything else throws `ArgumentException` ("CRON expression is invalid"), so a typo fails at startup rather than at 2 a.m. 2. It takes a **distributed lock** on the recurring job id. 3. It loads the record with that id, or creates an empty one. 4. It serializes the job (type, method, arguments) into the record. 5. It compares the cron and the time zone id with the stored ones; only if one of them changed, or the record carried an error, does it recompute the next execution time. 6. It writes only the fields that actually changed. The result is idempotent. Ten application instances calling it on startup converge on one definition, and an unchanged registration writes nothing. ## Why the explicit id matters | | Explicit id (current) | Id-less overload (`[Obsolete]`) | |---|---|---| | Key in storage | the string you pass, e.g. `nightly-sales-report` | `TypeName.MethodName`, derived from the expression | | Two schedules for one method | two definitions | the second silently overwrites the first | | Renaming the method | same id, record updated in place | new id; the old definition keeps firing until removed | | Status in 1.8.25 | supported | "Will be removed in 2.0.0" | The Hangfire README still shows `RecurringJob.AddOrUpdate(() => ..., Cron.Daily)` without an id; the source marks that overload obsolete. Hangfire 1.8.25 likewise marks obsolete the overloads that take a `TimeZoneInfo` and a queue as loose parameters, in favour of a `RecurringJobOptions` object. ## The rest of the lifecycle - **`RemoveIfExists(id)`** deletes the definition; the dashboard's delete button calls the same method. This is how a schedule is stopped for good: deleting the `AddOrUpdate` line from `Program.cs` leaves the stored record firing forever. Keep a `RemoveIfExists` call for retired ids until every environment has run it. - **`TriggerJob(id)`** creates and enqueues a background job from the definition now, returns its id (or `null` when no such recurring job exists), and keeps the regular schedule. `Trigger` is its obsolete predecessor. - **Changing the cron** in code and redeploying is enough: `AddOrUpdate` notices the different string and reschedules. ## Cron helpers `Cron` methods return plain five-field strings; they carry no time zone of their own. | Helper | String | |---|---| | `Cron.Minutely()` | `* * * * *` | | `Cron.Hourly()` | `0 * * * *` | | `Cron.Daily(2)` | `0 2 * * *` | | `Cron.Weekly()` | `0 0 * * 1` (Monday) | | `Cron.MinuteInterval(15)` | `*/15 * * * *` | | `Cron.Never()` | `0 0 31 2 *` (31 February) | `Cron.Never()` is a way to keep a definition that only runs when triggered by hand. The interval helpers were deprecated for a while and restored in 1.8.22, with a documentation remark that only divisors of the unit (every 2, 5, 10, 15 or 30 minutes) behave as expected. ## Registering them in ASP.NET Core The usual shape is a short block after `builder.Build()` that resolves `IRecurringJobManager` and calls `AddOrUpdate` for each schedule, with constant ids, plus `RemoveIfExists` for the ones being retired. Because the call is an upsert, it runs safely on every instance at every start.

  • Two instances start at the same moment and both call AddOrUpdate for the nightly report; is that a problem?
    No. `AddOrUpdate` takes a distributed lock on the recurring job id, reads the stored record and writes only the fields that differ, so both calls converge on one definition and the second usually writes nothing.
  • Support asks for tonight's sales report right now; what do you call?
    `RecurringJob.TriggerJob("nightly-sales-report")`, or `TriggerJob` on `IRecurringJobManagerV2`. It creates and enqueues a background job from the definition immediately and returns that job's id, or null for an unknown id; the nightly schedule carries on. `Trigger` is the obsolete older name.
  • A deploy changes only the body of the report method; does the schedule change?
    No. The stored job still names the same type and method, and the cron and time zone are unchanged, so `AddOrUpdate` keeps the next execution time. The next occurrence simply runs the new code the worker has loaded.

  • Calling RecurringJob.AddOrUpdate at every startup creates duplicate recurring jobs.
  • Deleting the AddOrUpdate line from Program.cs stops the schedule.
  • RecurringJob.AddOrUpdate with only a lambda and Cron.Daily is the current recommended form.
  • AddOrUpdate runs the job immediately and then follows the schedule.
  • An invalid cron string is only noticed when the first occurrence fails.

Assumes Hangfire 1.8.25, where every RecurringJob.AddOrUpdate overload without a recurringJobId is [Obsolete] and scheduled for removal in 2.0.0.