Build a .NET background service for scheduled tasks

A scheduled task often begins where an API request should not: at 2am, after a batch closes, or when a customer asks for a recurring report. A .NET worker keeps that work outside the web request, under a process that can start, stop, log, and recover predictably. The useful unit is not a timer inside a controller; it is a hosted background service with an explicit schedule and failure policy.

The smallest version uses .NET's Generic Host, the same hosting model as ASP.NET Core. BackgroundService gives you an ExecuteAsync method, while AddHostedService connects its lifetime to the application. The host starts the worker, passes a cancellation token during shutdown, and stops it when the process exits. This separation keeps request handling responsive and gives scheduled work a place for structured logs, metrics, and health checks.

Scheduling adds requirements that a plain Task.Delay does not solve. The job may need to run at a particular local time, recover from a temporary database outage, and avoid running twice when two instances are active. A useful design separates schedule calculation, job execution, and durable job state. That makes each part testable and lets an operator see whether a task is waiting, running, delayed, or complete.

This walkthrough uses a Worker Service, a UTC-based schedule calculation, and an Australian daily-report example. It also covers details that matter locally: Sydney and Melbourne run on Australian Eastern Time, Brisbane and Perth do not observe daylight saving, and Adelaide can sit half an hour away during part of the year. The same code can target an IANA zone such as Australia/Sydney instead of relying on the server's local clock.

Set up the worker project

Create a Worker Service with dotnet new worker -n ScheduledReports, then open it in your editor. Keep scheduling and business work in separate classes. The worker should coordinate timing, create a dependency scope, and call an IReportRunner; the runner can update SQL Server or call another service.

Replace the template's Program.cs with the generic host registration below. TimeProvider.System is registered so the clock can be replaced with a fake implementation in tests. Register scoped dependencies separately, such as builder.Services.AddScoped<IReportRunner, SqlReportRunner>();, and register the worker itself as a hosted service.

using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddHostedService<DailyReportWorker>();

await builder.Services.Build().RunAsync();

The worker template already references Microsoft.Extensions.Hosting; there is no need for a web server or an ASP.NET Core project. More general examples of building with .NET are available in the developer archive, while this project stays deliberately small enough to run as a console process.

Implement the scheduling loop

BackgroundService.ExecuteAsync is invoked once when the host starts. A long-lived worker keeps running inside that method until cancellation and calculates each next run within its loop. A fixed interval can answer “every ten minutes”, but it cannot cleanly represent “06:00 in Sydney on each day”, especially when clocks change.

Resolve the time zone and next run before waiting. The example uses Australia/Sydney, converts the current instant to local time, and stores the target as a DateTimeOffset. The delay uses TimeProvider, so unit tests can advance time without sleeping for hours.

internal sealed class DailyReportWorker(
    IServiceScopeFactory scopes,
    TimeProvider clock,
    ILogger<DailyReportWorker> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var zone = TimeZoneInfo.FindSystemTimeZoneById("Australia/Sydney");
        var next = NextRunAfter(clock.GetUtcNow(), zone, new TimeOnly(6, 0));

        while (!stoppingToken.IsCancellationRequested)
        {
            await Task.Delay(next - clock.GetUtcNow(), clock, stoppingToken);

            for (var attempt = 1; attempt <= 3; attempt++)
            {
                try
                {
                    await RunAsync(stoppingToken);
                    break;
                }
                catch (OperationCanceledException)
                    when (stoppingToken.IsCancellationRequested)
                {
                    throw;
                }
                catch (Exception exception)
                {
                    logger.LogError(
                        exception,
                        "Daily report attempt {Attempt} failed.",
                        attempt);

                    if (attempt < 3)
                    {
                        await Task.Delay(
                            TimeSpan.FromMinutes(attempt * 5),
                            clock,
                            stoppingToken);
                    }
                }
            }

            next = NextRunAfter(
                clock.GetUtcNow(),
                zone,
                new TimeOnly(6, 0));
        }
    }

    private async Task RunAsync(CancellationToken cancellationToken)
    {
        await using var scope = scopes.CreateAsyncScope();
        var runner = scope.ServiceProvider.GetRequiredService<IReportRunner>();
        await runner.RunAsync(cancellationToken);
    }

    private static DateTimeOffset NextRunAfter(
        DateTimeOffset now,
        TimeZoneInfo zone,
        TimeOnly runAt)
    {
        var localNow = TimeZoneInfo.ConvertTime(now, zone);
        var localRun = DateTime.SpecifyKind(
            localNow.Date + runAt.ToTimeSpan(),
            DateTimeKind.Unspecified);

        if (zone.IsInvalidTime(localRun))
            localRun = localRun.AddHours(1);

        var candidate = new DateTimeOffset(
            localRun,
            zone.GetUtcOffset(localRun));

        if (candidate <= now)
        {
            localRun = localRun.AddDays(1);
            candidate = new DateTimeOffset(
                localRun,
                zone.GetUtcOffset(localRun));
        }

        return candidate;
    }
}

The sample makes up to three attempts with short delays, then waits for the next daily run. Add jitter to retry delays and alert when all attempts are exhausted. The cancellation path exits cleanly when the host shuts down. Because scoped services such as a SQL Server DbContext cannot live for the worker's entire lifetime, RunAsync creates a scope for each attempt.

Apply Australian time-zone rules

Store the schedule and zone separately, then calculate the next execution in UTC. Australian daylight-saving rules vary by jurisdiction: NSW, Victoria, Tasmania, the ACT and South Australia change their clocks, while Queensland, Western Australia and the Northern Territory do not. Adelaide also uses a half-hour offset during daylight saving, and Darwin remains on UTC+9:30.

A schedule at 06:00 is safely outside the common clock-change window, but business rules may require a time near 02:00. During spring, a local time can be skipped; during autumn, it can occur twice. The sample moves an invalid time forward by one hour. For an ambiguous time, define whether the first or second occurrence wins, then test that policy explicitly.

Use IANA identifiers such as Australia/Sydney, Australia/Brisbane, Australia/Perth and Australia/Adelaide rather than abbreviations such as AEST. They also remove ambiguity around daylight-saving names. Unit-test the next-run calculation around both clock changes and include weekends and public holidays. For a business that starts around 09:00, an early report is available before the working day begins. Quartz.NET is a sensible upgrade when jobs need cron expressions, misfire policies or several schedules.

Protect job execution and personal data

Make every job idempotent before enabling retries. Give each execution a key such as daily-report:tenant-42:2025-07-14, record it in SQL Server, and enforce uniqueness. If the worker sends an invoice and then crashes before recording success, the next attempt must detect the completed operation instead of sending a duplicate. For external side effects, use provider idempotency keys or a transactional outbox where the provider supports them.

CREATE UNIQUE INDEX UX_JobRuns_JobKey
ON dbo.JobRuns (JobKey);

A job table should also contain the tenant, schedule, attempt count, status, next attempt and timestamps. Claim rows with a short database lease rather than holding a transaction open for the entire job. This prevents a crashed instance from blocking a schedule forever, although a distributed lock may still be needed when several worker replicas can claim the same logical job.

Australian privacy obligations belong in the design. Where the Privacy Act 1988 applies, the Australian Privacy Principles require organisations to limit collection, protect personal information, keep it secure and dispose of it appropriately. Do not place names, health details or access tokens in exception messages or ordinary logs. If a task sends commercial email, also assess the Spam Act 2003, including consent, sender identification and unsubscribe requirements. Define retention and breach-response steps before production data enters the worker.

Deploy and observe the worker

Package the worker as a container, run it on a Windows or Linux virtual machine, or deploy it as a container on Kubernetes. Microsoft Azure and AWS both have established Australian regions in Sydney and Melbourne, so an organisation can choose a local region for latency and contractual reasons. Move the run time and time-zone identifier into application configuration, but keep secrets in the platform's secret store. A container health check should verify that the host is running without assuming the worker is idle.

On Windows, run the executable as a Windows Service under a least-privilege identity. On Linux, use systemd and send SIGTERM during normal shutdown. Give the host enough time to cancel the token and let a short database operation finish. Long jobs should save a checkpoint and resume from it; they should not trap shutdown merely to appear successful. For reproducible Linux packaging and deployment workflows, the Nix workflows resource offers a useful adjacent pattern.

Export structured logs, traces and metrics through OpenTelemetry. At minimum, record the job name, execution key, attempt, duration, result and exception type. Alert when no successful run appears by the expected deadline, when retries are exhausted, or when the number of overdue jobs grows. A liveness probe answers “is the process alive?”; a separate readiness signal should reflect whether the scheduler can reach its database.

Run the first production schedule

Start with one read-only or easily reversible job. Run it locally against disposable data, then in staging with production-like time-zone and database settings. Execute the calculation for dates before and after both Australian clock changes, and confirm the selected UTC instant in logs. Add an alert before enabling the schedule, not after a missed report becomes visible to a customer.

Keep a short runbook beside the deployment. It should state the owner, expected run time, supported time zone, maximum runtime, retry count, data sources and manual recovery procedure. Verify SQL Server backup coverage, least-privilege access and log redaction. Record the deployment version and schedule configuration so an operator can reproduce a failed run with the same inputs.

Create the worker project today, implement one idempotent job with an explicit Australian time zone, prove it against a staging database, and then enable the production schedule.