BackgroundService

A base class for long-running background work.

What is BackgroundService?

BackgroundService is a base class that makes hosted services easy: override ExecuteAsync with a loop that runs until the app shuts down.

public class NightlyCleanup(ILogger<NightlyCleanup> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            logger.LogInformation("Cleaning up expired sessions");
            await Task.Delay(TimeSpan.FromHours(24), stoppingToken);
        }
    }
}

Level: Freelancer · More ASP.NET Core terms at this level

Updated