Scheduling background work on Windows: Task Scheduler vs. hosted services

  • csharp
  • dotnet

Every .NET application I have inherited on Windows came with the same question: “where does the nightly job run?” The answers were always one of two things, and the choice was almost always accidental. Either a console app wired into Task Scheduler, or a BackgroundService inside the always-running ASP.NET Core process. Both are fine. They are just fine for different jobs, and picking the wrong one produces a specific kind of slow-burning pain.

Hosted services: work tied to the lifetime of the app

A BackgroundService runs inside the host, so it gets dependency injection, configuration and logging for free, and it stops gracefully when the app stops. This is the right home for work that only makes sense while the application is up: dispatching an outbox table, refreshing a cache, polling a queue.

public sealed class OutboxDispatcher(IServiceScopeFactory scopes, ILogger<OutboxDispatcher> logger)
    : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromSeconds(15));
        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            try
            {
                // Scoped services (a DbContext, for instance) must not be
                // captured from the root container; create a scope per iteration.
                using var scope = scopes.CreateScope();
                var job = scope.ServiceProvider.GetRequiredService<DispatchOutboxJob>();
                await job.RunAsync(stoppingToken);
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                return; // normal shutdown, not an error
            }
            catch (Exception ex)
            {
                // Never let one failed iteration kill the loop.
                logger.LogError(ex, "Outbox dispatch failed; retrying on the next tick.");
            }
        }
    }
}

// Program.cs
builder.Services.AddHostedService<OutboxDispatcher>();

The three details that matter: PeriodicTimer instead of Task.Delay, so a slow iteration does not cause drift; a new scope per iteration, because a scoped DbContext kept alive for days will happily serve stale entities; and the catch-all that logs and continues, because an unhandled exception in ExecuteAsync stops the host by default.

Task Scheduler: work that must happen at a wall-clock time

Some jobs are not about the application at all: a 02:00 reconciliation, an export that must exist before the office opens, a cleanup that has to run even if the app crashed at midnight. For these, a plain console app plus Task Scheduler is still the better tool. The job runs in its own process, it is visible in the scheduler’s UI to whoever is on call, and it survives application restarts by definition.

schtasks /Create /TN "NightlyReconciliation" /SC DAILY /ST 02:00 ^
  /TR "C:\Jobs\Reconciliation.exe --date yesterday" /F

Three settings in the task definition are worth more than the rest of the dialog combined:

  • Run whether user is logged on or not, with a service account, otherwise the job silently does nothing after a reboot.
  • Start the task only if the computer is on AC power: uncheck it on anything that might be a laptop.
  • If the task fails, restart every 1 minute, and in the console app, return a non-zero exit code on failure. The scheduler records the last run result, and that number is what monitoring reads.

How I decide

Question Hosted service Task Scheduler
Interval under a minute yes awkward
Must run at an exact wall-clock time possible, but you write the wait logic built in
Needs DI, config, EF DbContext from the app trivial manual bootstrap
Must run when the app is down no yes
Needs its own exit code for monitoring wrap it yourself built in

The mistake I see most often is a daily 02:00 job implemented as a hosted service with Task.Delay until two in the morning, in an app pool that may be recycled, on a box that may be patched that night. The second most common is a 15-second poll implemented as a scheduled task that spawns a new process every 15 seconds. Neither is wrong technically; both fight their tool.

One last note: if the host itself needs to run as a Windows Service, Microsoft.Extensions.Hosting.WindowsServices with builder.Host.UseWindowsService() is the one-line way to get a hosted service that survives logoff. That solves the “always on” part for the app; it does not turn the app into a scheduler.