ASP.NET Core Interview Question #167
How can periodic background work be implemented safely?
Logging, Error Handling & Background Services Mid-Level Intermediate
Quick Interview Answer
Periodic work can be implemented with a BackgroundService and PeriodicTimer. Each iteration should observe the cancellation token, handle failures deliberately, and avoid overlapping executions unless concurrency is intentional.
Detailed Explanation
Periodic work can be implemented with a BackgroundService and PeriodicTimer. Each iteration should observe the cancellation token, handle failures deliberately, and avoid overlapping executions unless concurrency is intentional.
If a job requires durable scheduling, retries across process restarts, distributed coordination, or exactly-once-like business guarantees, an in-process timer alone may be insufficient. A persistent job scheduler or queue can be more appropriate.
The worker should also avoid holding scoped services between iterations.
Code Example
public class ReportWorker : BackgroundService
{
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(
TimeSpan.FromMinutes(10));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
await GenerateReportsAsync(stoppingToken);
}
}
}