How to implement a background task with hosted services in ASP.NET Core

A background task can run a task or a function in period times. Sometimes on your website, you want to run a task in the background in a specific period time without your interference, when your project is running. For example, in a period of time, you want to send Emil or SMS to users.

  1. Create a new project in ASP.NET Core
  2. Add a .cs file ServiceTime.cs called and copy below codes:
public class ServiceTime: IHostedService,IDisposable
    {
        private int _counter1 = 0;
        private int _counter2 = 0;
        private readonly ILogger<ServiceTime> _logger;
        private Timer _timer;

        public ServiceTime(ILogger<ServiceTime> logger)
        {
            _logger = logger;
        }

        public Task StartAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Service time is running.");

            _timer = new Timer(DoTask1, null, TimeSpan.Zero,

               TimeSpan.FromSeconds(3));


            _timer = new Timer(DoTask2, null, TimeSpan.Zero,

              TimeSpan.FromSeconds(10));

            return Task.CompletedTask;
        }

        private void DoTask1(object state)
        {   
            var count = Interlocked.Increment(ref _counter2);
            _logger.LogInformation(

              "Service time is doing task 1. Count: {Count}", count);

            // Do something 1

        }

        private void DoTask2(object state)
        {
            var count = Interlocked.Increment(ref _counter1);

            _logger.LogInformation(

                "Service time is doing task 2. Count: {Count}", count);

            // Do something 2

        }

        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();

        }
    }
  1. Add below code in Startup
    services.AddHostedService<ServiceTime>();
  2. Run the project and see the result:

 

Recent Comments