How to run backgroundservice on a timer in asp net core 2 1


ASP.NET is a popular programming language used for web applications. In this article, we will explore how to run a service on a timer in ASP.NET Core 2.1.

Background Services in ASP.NET Core

Background services are long-running tasks that run independently of the user interface. They are typically used for tasks such as sending emails, processing data, or performing periodic maintenance tasks.

In ASP.NET Core, background services can be implemented using the IHostedService interface. This interface provides methods for starting and stopping the background service.

Running a Background Service on a Timer

To run a background service on a timer, we can use the Timer class from the .Threading namespace. This class allows us to execute a method at regular .

Let's take a look at an example:

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.;

public class MyBackgroundService : IHostedService, IDisposable
     Timer _timer;

    public Task StartAsync(CancellationToken cancellationToken)
        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
        return Task.CompletedTask;

    private void DoWork(object state)
        // Perform background task here

    public Task StopAsync(CancellationToken cancellationToken)
        _timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;

    public void ()

In this example, we create a class called MyBackgroundService that implements the IHostedService interface. The StartAsync method is called when the background service , and the StopAsync method is called when the service stops.

In the StartAsync method, we create a new instance of the Timer class and specify the DoWork method as the callback method. We set the delay to TimeSpan.Zero and the interval to TimeSpan.FromSeconds(5), which means the DoWork method will be executed every 5 seconds.

The DoWork method is where we perform the actual background task. You can replace the comment with your own code to perform the desired task.

In the StopAsync method, we stop the timer by calling the Change method with Timeout.Infinite as the due time and 0 as the period. This effectively stops the timer from executing the DoWork method.

Finally, in the Dispose method, we dispose of the timer to release any it may be holding.


In this article, we have learned how to run a background service on a timer in ASP.NET Core 2.1. By using the Timer class and implementing the IHostedService interface, we can easily execute background tasks at regular intervals.

Remember to adapt the code to your specific requirements and add any necessary error handling or additional functionality.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents