Background Jobs in ASP.NET Core with BackgroundService and PeriodicTimer

Run scheduled work inside your ASP.NET Core app: BackgroundService, PeriodicTimer, scoped DbContext, safe reruns, and when to reach for Hangfire.

R M Shahidul Islam Shahed · 4 min read

Every app ends up with work that shouldn't happen during a request: publishing scheduled posts, cleaning up old data, sending queued emails. You don't need a separate service or a job framework to start. ASP.NET Core's BackgroundService and .NET's PeriodicTimer run that work inside your app reliably, if you get a few details right. This guide builds two real jobs and covers those details.

A job that runs every minute

BackgroundService gives you one method, ExecuteAsync, that runs for the lifetime of the app. PeriodicTimer ticks at a fixed interval without overlapping runs.

csharp
public sealed class ScheduledPublishingJob(
    IServiceScopeFactory scopes,
    ILogger<ScheduledPublishingJob> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromSeconds(60));
        do
        {
            await RunOnceAsync(stoppingToken);
        }
        while (await timer.WaitForNextTickAsync(stoppingToken));
    }

    private async Task RunOnceAsync(CancellationToken ct)
    {
        try
        {
            await using var scope = scopes.CreateAsyncScope();
            var posts = scope.ServiceProvider.GetRequiredService<IPostService>();
            var count = await posts.PublishDueAsync(ct);
            if (count > 0)
            {
                logger.LogInformation("Published {Count} scheduled posts", count);
            }
        }
        catch (OperationCanceledException) when (ct.IsCancellationRequested)
        {
            // the app is stopping
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Scheduled publishing failed");
        }
    }
}
csharp
builder.Services.AddHostedService<ScheduledPublishingJob>();

The do … while runs once at startup, then on every tick. WaitForNextTickAsync returns false when the app stops, which ends the loop cleanly.

Detail 1: create a scope per run

Hosted services are singletons. DbContext is scoped and not thread-safe, so you can't inject it into the job directly. Create a scope for each run and resolve what you need from it. Each run then gets a fresh context, and its tracked entities don't pile up for the life of the app.

Detail 2: never let an exception escape

Since .NET 6, an unhandled exception in ExecuteAsync stops the whole app by default (BackgroundServiceExceptionBehavior.StopHost). One bad row shouldn't take your website down. Catch and log inside each run, and let the next tick try again.

Detail 3: make each run safe to repeat

Your app may run on two servers, or restart halfway through a run. Write the job so running it twice does no harm. A conditional update does the work and the check in one statement:

csharp
public async Task<int> PublishDueAsync(CancellationToken ct)
{
    var now = clock.UtcNow;
    return await db.Posts
        .Where(p => p.Status == PostStatus.Scheduled && p.PublishAtUtc <= now)
        .ExecuteUpdateAsync(s => s
            .SetProperty(p => p.Status, PostStatus.Published)
            .SetProperty(p => p.FirstPublishedAtUtc, p => p.FirstPublishedAtUtc ?? p.PublishAtUtc), ct);
}

If two servers run it at the same moment, the second one's WHERE matches nothing, because the first already changed the status. No locks, no duplicates.

A daily job at a fixed hour

PeriodicTimer is for intervals. For "every day at 03:00 UTC", work out the delay to the next run:

csharp
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        var now = time.GetUtcNow().UtcDateTime;
        var next = now.Date.AddHours(3);
        if (next <= now) next = next.AddDays(1);

        try
        {
            await Task.Delay(next - now, time, stoppingToken);
            await CleanupAsync(stoppingToken);
        }
        catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
        {
            return;
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Cleanup failed");
        }
    }
}

Recomputing the delay on each loop keeps the schedule correct after a slow run. Passing a TimeProvider to Task.Delay lets tests control time.

The cleanup itself is two bulk deletes, which run in SQL without loading rows:

csharp
await db.Subscribers
    .Where(s => s.Status == SubscriberStatus.Pending && s.CreatedAtUtc < now.AddDays(-30))
    .ExecuteDeleteAsync(ct);

Don't block startup

ExecuteAsync runs during startup until its first await. Long synchronous work before that delays the app from serving requests. The examples above await straight away; if a job needs slow setup, start with await Task.Yield();.

Log what matters

For each run, log start, how many items were affected and how long it took, but only when something happened, so a job that runs every minute doesn't flood your logs. A failing job goes unnoticed without a log line at Error level.

When to reach for a job library

In-process jobs are a good fit for small, frequent, idempotent work. Move to a library such as Hangfire or Quartz.NET when you need:

  • Persistence: jobs survive restarts and are retried with back-off.
  • A dashboard to see failures and rerun jobs by hand.
  • One-off scheduled jobs ("send this email in three days") rather than recurring sweeps.
  • Distributed locks, if a job can't be made idempotent.

Many apps never need them. A scheduled sweep that's safe to repeat covers publishing, cleanup and roll-ups.

Test the work, not the timer

Keep the logic in a service method (PublishDueAsync, CleanupAsync) and test that with a fake clock and a real database. The hosted service then only decides when to call it, and has almost nothing left to break.

Wrapping up

BackgroundService plus PeriodicTimer, a new scope per run, exceptions caught inside the run, and work that's safe to repeat: that's a reliable job runner with no extra infrastructure. Add a job library only when you need persistence, retries or a dashboard.

Keep reading

All articles →
Architecture & Production .NET

Thin Controllers and Feature Folders: Organising an ASP.NET Core App

Keep controllers to routing, put rules in services, map by hand and group files by feature. A structure that stays readable as the app grows.

4 min read
ASP.NET Core & Web APIs

Output Caching in ASP.NET Core: Tags, Eviction and the Traps

Cache whole pages on the server, clear them the moment content changes, and avoid the antiforgery and nonce traps that break cached HTML.

4 min read
SaaS & Indie Monetisation

Pricing Plans and Usage Limits in an ASP.NET Core SaaS

Model Free, Pro and Business plans in code, enforce feature flags and usage limits per tenant, and show a friendly upgrade prompt instead of an error.

4 min read