For a recurring job in an ASP.NET Core BackgroundService, why prefer PeriodicTimer over Task.Delay or System.Threading.Timer, and how does WaitForNextTickAsync behave?
answer
- one awaiter, no overlapping runs
- missed ticks coalesce into one
- ValueTask<bool>: false after Dispose
- cancelled token throws, not false
- TimeProvider overload for tests
basics
~20 sPeriodicTimer keeps a fixed cadence without overlapping runs: the loop awaits WaitForNextTickAsync(stoppingToken), which returns true per tick, false once the timer is disposed, and throws when the token is cancelled. Missed ticks coalesce into one.
solid answer
~40 s`PeriodicTimer` is built for an `async` loop: `while (await timer.WaitForNextTickAsync(stoppingToken))` runs one iteration per tick, and the next wait starts only when the iteration ends, so runs never overlap. Unlike `Task.Delay(period)` after the work, the cadence does not drift by the work's duration. Unlike `System.Threading.Timer`, there is no callback that can fire again while a slow run is still going. `WaitForNextTickAsync` returns `ValueTask<bool>`: `true` on a tick, `false` once the timer is disposed, and it throws `OperationCanceledException` when the token is cancelled. Ticks missed during a long run coalesce into a single pending tick. Only one wait may be in flight at a time. The `(TimeSpan, TimeProvider)` constructor lets a test drive time with `FakeTimeProvider`.
code
csharp · 22 linespublic sealed class InvoiceReminderService(
IServiceScopeFactory scopeFactory,
ILogger<InvoiceReminderService> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromHours(1));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
await using var scope = scopeFactory.CreateAsyncScope();
var sender = scope.ServiceProvider.GetRequiredService<ReminderSender>();
await sender.SendDueRemindersAsync(stoppingToken);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Invoice reminder run failed");
}
}
}
}go deeper
Recall the loop shape: create a PeriodicTimer, then while await timer.WaitForNextTickAsync(stoppingToken) do the work.
Explain the return values, coalesced ticks, the single-consumer rule, and why a scope is created per tick for scoped services.
Show the failure modes of the alternatives (drift, overlapping callbacks, an exception escaping a Timer callback) and make each run idempotent so an extra tick is harmless.
Decide where a hand-written timer loop stops being enough and calendar schedules, retries and visibility justify a dedicated scheduler.
## Three ways to repeat work A recurring job in a hosted service, such as sending invoice reminders in a water-utility billing app, needs a clock. .NET offers three common ones, and they fail differently: | Approach | Cadence | Overlap | Errors | |---|---|---|---| | `await Task.Delay(period, token)` after each run | period **plus** run time, so it drifts | none | flow through your `async` loop | | `System.Threading.Timer` with a callback | fixed | a slow callback can still be running when the next one fires | the callback is a sync `void` delegate; an escaping exception is an unhandled thread-pool exception, which by default terminates the process | | `PeriodicTimer` with `WaitForNextTickAsync` | fixed | none: one awaiter, one iteration at a time | flow through your `async` loop | `PeriodicTimer` combines the fixed cadence of a timer with the sequential, awaitable shape of a loop, which is why it fits `BackgroundService.ExecuteAsync`. ## How WaitForNextTickAsync behaves - **Return type** `ValueTask<bool>`. `true` means a tick happened; `false` means the timer was stopped with `Dispose()`. Disposing ends the loop cleanly. - **Cancellation throws.** If the token passed in is cancelled, the wait completes as cancelled and `await` throws `OperationCanceledException`. It does not return `false`. In a `BackgroundService` that is the normal stop path. - **The first tick comes after one period**, not immediately. Do a first run before the loop if the job must run at start-up. - **Coalescing.** The timer behaves like an auto-reset event: if three periods pass during one slow iteration, the next wait completes at once with `true`, once. There is no backlog of missed ticks. - **Single consumer.** Only one `WaitForNextTickAsync` call may be outstanding; a second concurrent call throws `InvalidOperationException`. - **Adjustable.** The `Period` property can be changed while the loop runs, for example from configuration. ## Testability The constructor `PeriodicTimer(TimeSpan period, TimeProvider timeProvider)` takes a `TimeProvider`. Register `TimeProvider.System` in production; in a test, pass `FakeTimeProvider` from the `Microsoft.Extensions.TimeProvider.Testing` package and call `Advance(TimeSpan)` to fire ticks without waiting real hours. `Task.Delay` has matching `TimeProvider` overloads. ## The reminder loop and its scoped services The hosted service is a singleton, while the code that queries overdue invoices and sends mail uses a `DbContext`, which is scoped. The loop therefore creates a scope **per tick** with `IServiceScopeFactory.CreateAsyncScope()`, resolves the scoped sender from it, and disposes it at the end of the iteration. A fresh context per run also avoids an ever-growing change tracker. ## Common mistakes - **Forgetting `using` on the timer.** The loop usually ends with the method, but an undisposed timer keeps its underlying timer alive until finalisation; `using var timer = ...` releases it deterministically. - **Calling `WaitForNextTickAsync()` without the token.** Shutdown then waits for the next tick, up to a whole period, unless something disposes the timer. - **Expecting a run at start-up.** The first tick arrives one period after construction. A `do { ... } while (await timer.WaitForNextTickAsync(stoppingToken));` loop runs once immediately and then on each tick. - **Letting one failure end the loop.** An exception from the work escapes `ExecuteAsync` and, by default, stops the host; catch per iteration. ## Nightly is not a period `PeriodicTimer` knows intervals, not clock times. Two honest options: 1. Tick often (say hourly) and let the job select only invoices that are **due and not yet reminded**, so an extra tick does nothing. 2. Compute the delay until the next 02:00 and await that, recomputing after each run. When jobs need calendar schedules, retries and a dashboard, that is a scheduler's work rather than a hand-written loop.
- How do you unit-test a PeriodicTimer loop without waiting an hour?Construct the timer with the `PeriodicTimer(TimeSpan, TimeProvider)` overload and inject the `TimeProvider`. In the test pass `FakeTimeProvider` from `Microsoft.Extensions.TimeProvider.Testing` and call `Advance(TimeSpan.FromHours(1))`; the pending `WaitForNextTickAsync` completes, and the test asserts on the fake sender.
- Can two loops share one PeriodicTimer to process work in parallel?No. A `PeriodicTimer` allows one outstanding `WaitForNextTickAsync`; a second concurrent call throws `InvalidOperationException`. For parallel work, one loop waits on the timer and fans the work out, or each loop owns its own timer.
- PeriodicTimer.WaitForNextTickAsync returns false when the token is cancelled
- PeriodicTimer replays every missed tick after a slow iteration
- PeriodicTimer fires its first tick immediately when created
- System.Threading.Timer never overlaps because the callback is awaited
- Task.Delay(period) after the work keeps an exact cadence