If you need a background task within .Net Core to be run at set times we can use the Hosted Service provided from the service within .Net Core.
A timed background task makes use of the System.Threading.Timer class. The timer triggers the task’s DoWork
method. The timer is disabled on StopAsync
and disposed when the service container is disposed on Dispose
:
public class TimedHostedService : IHostedService, IDisposable { private int executionCount = 0; private readonly ILogger<TimedHostedService> _logger; private Timer _timer; public TimedHostedService(ILogger<TimedHostedService> logger) { _logger = logger; } public Task StartAsync(CancellationToken stoppingToken) { _logger.LogInformation("Timed Hosted Service running."); _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5)); return Task.CompletedTask; } private void DoWork(object state) { var count = Interlocked.Increment(ref executionCount); _logger.LogInformation( "Timed Hosted Service is working. Count: {Count}", count); } public Task StopAsync(CancellationToken stoppingToken) { _logger.LogInformation("Timed Hosted Service is stopping."); _timer?.Change(Timeout.Infinite, 0); return Task.CompletedTask; } public void Dispose() { _timer?.Dispose(); } }
The Timer doesn’t wait for previous executions of DoWork
to finish, so the approach shown might not be suitable for every scenario. Interlocked.Increment is used to increment the execution counter as an atomic operation, which ensures that multiple threads don’t update executionCount
concurrently.
The service is registered in IHostBuilder.ConfigureServices
(Program.cs) with the AddHostedService
extension method:
services.AddHostedService<TimedHostedService>();