How to schedule background tasks (jobs) in ASP.NET Core?

ASP.NetServer Side ProgrammingProgramming

Background tasks, also called as jobs, are essentially services that aren’t meant to execute during a normal flow of the application, such as sending email confirmations or periodically cleaning up the database to purge the inactive accounts. These jobs are not meant to interact with the customers or process user input. Rather, they run in the background, handling items from a queue or executing a long-running process.

A primary advantage of performing these tasks in a background job or service, you can keep the application responsive. For example, when a user signs up, instead of sending them an email in the same request, you can schedule a background job that will send the email to the user.

ASP.NET Core supports background tasks, by providing an abstraction for running a task in the background when the application starts. In ASP.NET Core, these types of background tasks are called Hosted Services, because you host them within your application.

You can use the IHostedService interface to run tasks in the background. The hosted service simply indicates a class that contains background task logic. When the application starts, you register multiple background tasks that run in the background while the application is running. When the application stops, the services are stopped as well. Even Kestrel, the ASP.NET Core server, runs as an IHostedService.

The IHostedService interface contains two methods:

  • StartAsync(CancellationToken): provides the logic to start the background task.

  • StopAsync(CancellationToken): called before the application stops. It provides the logic to end the background task.


Here is an example that illustrates the configuration of a hosted service.

public class Program{
   public static void Main(string[] args){

   public static IHostBuilder CreateHostBuilder(string[] args) =>
      .ConfigureWebHostDefaults(webBuilder =>{
      .ConfigureServices(services =>{

You can implement the IHostedService interface using the BackgroundService class as the base class. It contains an ExecuteAsync(CancellationToken) that is called to run the background service. The method returns a Task object that represents the background service lifetime.

Published on 22-Jun-2021 14:35:28