, 11 min read, by

BackgroundService in .NET 10: PeriodicTimer, a Scope per Run and a Clean Stop under docker stop

Worker boilerplate with PeriodicTimer and a scope per run: measured stop times after SIGTERM, exit code 0 after a crash, the variable for the shutdown timeout.

A dotnet new worker runs right after dotnet run. The important questions only come up in the container: What happens to a run that is in progress when docker stop arrives? What does the host do when the job throws an exception? And why does a DbContext in the constructor get caught locally, but not in the container? I built the boilerplate on 14 November 2026, stopped it with SIGTERM and crashed it on purpose. The frame for an existing application is in my post on the migration from .NET 8 to .NET 10.

The worker template is enough for dotnet run, not for docker stop

The template as of SDK 10.0.401

My test ran in a throwaway container from mcr.microsoft.com/dotnet/sdk:10.0 with SDK 10.0.401 and runtime 10.0.12 on linux/arm64 with 2 CPUs. On the same day Microsoft already listed runtime 10.0.15 and SDK 10.0.404; everything applies to the tested state. dotnet new worker creates a project with the Microsoft.NET.Sdk.Worker SDK, the target framework net10.0 and a package reference to Microsoft.Extensions.Hosting in the version of the SDK level, 10.0.12 in my case. On NuGet, 10.0.15 is the highest version of the 10.x line. The template's Worker.cs is a while loop with Task.Delay(1000, stoppingToken).

Since 10 November 2026 there is .NET 11 as an STS release. .NET 10 remains LTS, and both lines end on 14 November 2028. I stay on .NET 10; one finding further down hangs on this choice: the exit code after an unhandled exception.

What the template leaves open

The template worker has no scope for scoped services such as a DbContext, no error handling in the loop, and its stop behaviour is only as good as the next await with a token. The docs are clear: a hosted service is a singleton and does not receive scoped services through the constructor, and ExecuteAsync should return "promptly" after cancellation, otherwise the service ends "ungracefully" at the shutdown timeout.

ReportWorker: one run, one scope, one timer

Program.cs and ReportWorker.cs

Registration as in the template, only the job is added as a scoped service:

using MyWorker;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddScoped<IReportJob, ReportJob>();   // scoped, e.g. with a DbContext
builder.Services.AddHostedService<ReportWorker>();     // singleton according to the docs

var host = builder.Build();
host.Run();

The worker takes its own scope per run and catches errors per run:

namespace MyWorker;

public interface IReportJob
{
    Task RunAsync(CancellationToken stoppingToken);
}

public sealed class ReportJob(ILogger<ReportJob> logger) : IReportJob
{
    public Task RunAsync(CancellationToken stoppingToken)
    {
        logger.LogInformation("Job laeuft, Zeit {Time}", DateTimeOffset.Now);
        return Task.CompletedTask;
    }
}

public sealed class ReportWorker(
    IServiceScopeFactory scopeFactory,
    ILogger<ReportWorker> logger) : BackgroundService
{
    private static readonly TimeSpan Period = TimeSpan.FromSeconds(30);

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using PeriodicTimer timer = new(Period);

        try
        {
            do
            {
                try
                {
                    await using AsyncServiceScope scope = scopeFactory.CreateAsyncScope();
                    IReportJob job = scope.ServiceProvider.GetRequiredService<IReportJob>();
                    await job.RunAsync(stoppingToken);
                }
                catch (Exception ex) when (ex is not OperationCanceledException)
                {
                    logger.LogError(ex, "Durchlauf fehlgeschlagen, naechster Versuch beim naechsten Tick");
                }
            }
            while (await timer.WaitForNextTickAsync(stoppingToken));
        }
        catch (OperationCanceledException)
        {
            logger.LogInformation("ReportWorker wird beendet.");
        }
    }
}

do ... while (await timer.WaitForNextTickAsync(stoppingToken)) executes the first run immediately and then waits for the next tick, not a full period after the run ends; if a run takes longer than the period, the next one starts immediately. WaitForNextTickAsync returns true on a tick, false after Dispose, and enters the Canceled state on cancellation; that is why the outer block treats the OperationCanceledException as a normal end. The inner catch catches everything else so that the worker continues at the next tick. One gap remains: an OperationCanceledException from the job's own cancellation token passes the filter as well, ExecuteAsync returns, and according to the worker docs the host keeps running indefinitely without StopApplication, with a dead worker. If you use your own tokens, filter with when (!stoppingToken.IsCancellationRequested) instead; I only tested the version printed above.

Why PeriodicTimer and not System.Threading.Timer

The older variant from the hosted services docs uses a Timer callback which, according to the same docs, does not wait for the previous execution to finish. The API docs require reentrant callbacks because the callback can run on two thread pool threads simultaneously if the interval is shorter than its runtime. For a job that writes to a database, that is wrong. PeriodicTimer is intended for a single consumer, and multiple due ticks are coalesced into one: an overlong run gets at most one immediately pending tick, never a parallel run.

System.Threading.Timer PeriodicTimer
Call model callback on a thread pool thread await WaitForNextTickAsync in your own loop
Overlapping runs possible, callback must be reentrant no, one consumer, ticks are coalesced
Stopping dispose the timer, a running callback continues cancel via stoppingToken, loop ends
Testability your own rework needed constructor with TimeProvider

Measured: how long the process lives after SIGTERM

Five cases, one boilerplate

This is how I measured: the process ran directly in the container as dotnet bin/Release/net10.0/MyWorker.dll, after 3 seconds of runtime came kill -TERM, the stop time is the time from kill to process end in milliseconds, and the exit code comes from wait. Period 5 instead of 30 seconds, otherwise the code as printed; no docker stop, single measurements.

Case Run Setting Time to process end Exit code Last log line
A returns immediately default 98 ms 0 "ReportWorker wird beendet."
B Task.Delay(20 s) without token default (ShutdownTimeout 30 s) 17439 ms 0 "ReportWorker wird beendet."
C as B DOTNET_SHUTDOWNTIMEOUTSECONDS=4 4049 ms 0 "Application is shutting down..."
D as B HostOptions__ShutdownTimeout=00:00:04 17415 ms 0 "ReportWorker wird beendet."
E Task.Delay(60 s) without token default 30055 ms 0 "Application is shutting down..."

Case A is the normal case: the job honours the token or waits in the timer, and the process is gone after about 0.1 seconds. Case B is what I fear in the container: a run that ignores the token holds the process until its end, a 20 second job minus 3 seconds of lead time. That is above the default grace of 10 seconds after which docker stop sends SIGKILL according to the Docker docs; Docker would therefore have killed this run, a conclusion from measurement plus docs. Case E shows the host's limit: after 30 seconds it aborts, "ReportWorker wird beendet." no longer appears, I saw no separate timeout log line in this run, and the exit code is still 0. Case A verbatim, timestamps from the test script, not from the logger:

20:20:45.806 info: Microsoft.Hosting.Lifetime[0]
20:20:45.809       Application is shutting down...
20:20:45.853 info: MyWorker.ReportWorker[0]
20:20:45.858       ReportWorker wird beendet.

DOTNET_SHUTDOWNTIMEOUTSECONDS works, HostOptions__ShutdownTimeout does not

Cases C and D differ only in the environment variable. The host reads configuration from variables with the DOTNET_ prefix; the generic host docs list the key shutdownTimeoutSeconds with the variable {PREFIX_}SHUTDOWNTIMEOUTSECONDS for the shutdown timeout. DOTNET_SHUTDOWNTIMEOUTSECONDS=4 ended the process after 4049 ms, the obvious options binding HostOptions__ShutdownTimeout=00:00:04 changed nothing. Via the environment, then, use the DOTNET_ variable, as an integer in seconds; in code, the HostOptions.ShutdownTimeout property.

Two errors the container keeps quiet about

Unhandled exception: the host stops with exit code 0

For this test I disabled the inner catch and let the job throw an InvalidOperationException. Output verbatim, stack trace lines removed:

fail: Microsoft.Extensions.Hosting.Internal.Host[9]
      BackgroundService failed
      System.InvalidOperationException: Datenbank nicht erreichbar
crit: Microsoft.Extensions.Hosting.Internal.Host[10]
      The HostOptions.BackgroundServiceExceptionBehavior is configured to StopHost. A BackgroundService has thrown an unhandled exception, and the IHost instance is stopping. To avoid this behavior, configure this to Ignore; however the BackgroundService will not be restarted.
      System.InvalidOperationException: Datenbank nicht erreichbar
info: Microsoft.Hosting.Lifetime[0]
      Application is shutting down...

After that the process ended by itself, exit code 0. The cause: since .NET 6 the host logs an exception from ExecuteAsync and stops the host by default (BackgroundServiceExceptionBehavior.StopHost). On .NET 10 this does not become a failure status; the breaking change page for .NET 11 calls the old behaviour "usually ... a success exit code (zero)". For Docker that means: restart: on-failure only restarts on a failure exit code, so this container would stay down. The restart modes are in my post on HEALTHCHECK and restart_policy. From .NET 11 on, RunAsync throws in this case, and the process typically ends with a non-zero exit code, unless RunAsync sits inside a try-catch; I did not test that.

That is why I catch errors per run in the loop instead of letting the host die. The alternative BackgroundServiceExceptionBehavior.Ignore is worse: according to the same message the service is then not restarted. With the catch active the worker kept running and tried again at the next tick (timestamps from the test script; during the test the log message still read naechster Versuch in {Period}):

20:20:58.630 fail: MyWorker.ReportWorker[0]
20:20:58.635       Durchlauf fehlgeschlagen, naechster Versuch in 00:00:05
20:20:58.638       System.InvalidOperationException: Datenbank nicht erreichbar
20:21:03.573 fail: MyWorker.ReportWorker[0]
20:21:03.576       Durchlauf fehlgeschlagen, naechster Versuch in 00:00:05

Scoped service in the constructor: by default an error only in Development

Then I additionally injected IReportJob into the constructor of ReportWorker. The build passes. With DOTNET_ENVIRONMENT=Development the start aborts, exit code 134:

Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: MyWorker.ReportWorker': Cannot consume scoped service 'MyWorker.IReportJob' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.)

Without the variable, that is as Production, the same build starts without a message. The scoped service then lives as long as the worker. The cause is in the DI docs: by default the default provider checks only in the Development environment that scoped services are not injected into singletons. According to the API docs, the default of ServiceProviderOptions.ValidateScopes is IsDevelopment; set to true, it also checks in Production. The template sets DOTNET_ENVIRONMENT=Development in launchSettings.json, docker run sets nothing, and the host's default is Production. Without that option the error stays invisible exactly where it does harm.

Dockerfile and compose.yaml as a sketch

Exec form and runtime image

I did not build either; the structure follows Microsoft's worker docs, and I checked the tags against the registry.

FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY MyWorker.csproj .
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /app/publish --no-restore

FROM mcr.microsoft.com/dotnet/runtime:10.0 AS final
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "MyWorker.dll"]

The exec form of the ENTRYPOINT is not a matter of style: according to the Dockerfile reference, the shell form starts the process as a subcommand of /bin/sh -c, "which does not pass signals", and it does not receive a SIGTERM from docker stop. ConsoleLifetime then never sees the signal. The base image is runtime; a worker without an HTTP endpoint does not need aspnet. I explain build and runtime stages in my post on the multi-stage Dockerfile for Node and .NET.

Putting stop_grace_period above the ShutdownTimeout

services:
  worker:
    build: .
    restart: unless-stopped
    stop_grace_period: 45s
    environment:
      DOTNET_SHUTDOWNTIMEOUTSECONDS: "40"
docker stop                                                           
  |                                                                   
  | SIGTERM                                  stop_grace_period: 45 s  
  v                                          then SIGKILL             
ConsoleLifetime --> StopApplication() --> Host.StopAsync()            
                                            |  ShutdownTimeout: 40 s  
                                            v                         
                                          stoppingToken is cancelled  
                                            |                         
                                            v                         
                                          ExecuteAsync returns, exit 0

The numbers 40 and 45 are my choice, not from the docs: the host timeout sits below the grace period so that the host controls its own timeout before Docker sends SIGKILL. Only the defaults are documented, 30 seconds in the host and 10 seconds in Docker and Compose. restart: unless-stopped instead of on-failure follows from the exit code 0: it restarts irrespective of the exit code as long as the service has not been stopped or removed.

Questions about the worker in the container

Why does the host keep running when ExecuteAsync returns?

That is by design: the worker docs say that without a call to StopApplication the host continues to run indefinitely. For a job that should run only once, inject IHostApplicationLifetime and call StopApplication() at the end.

Can the worker run inside the web API?

Yes, with the same AddHostedService on WebApplicationBuilder.Services. According to the docs, StartAsync then runs before pipeline configuration and server start, and the service is activated once per app start.

Does synchronous code at the start of ExecuteAsync block startup?

Not on .NET 10 any more. According to the breaking change page, the synchronous part before the first await previously ran on the main thread and kept other services from starting; since .NET 10 all of ExecuteAsync runs on a background thread. My counter-test with Thread.Sleep(5000) as the first line showed "Application started" immediately and the line after the sleep about 5 seconds later. If you deliberately want to work synchronously before startup, override StartAsync and call base.StartAsync afterwards.

Sources and the next step

Next step

The worker is built in the same CI as in my post on GitHub Actions for .NET with push to GHCR. For projects in .NET development, I recommend a stop test like the one above as an acceptance criterion: a worker that has not finished within the grace period after docker stop should not go to production.

Sources I checked

Note: The articles on this blog are produced with the help of AI and are editorially reviewed before publication. Editorial responsibility lies with Emre Yurtbay (see the legal notice).

Let's talk

In a free initial consultation, you describe your situation to me. I will give you an initial assessment of how I can support you.

Request a free initial consultation