When developing web applications, you will often need to schedule and run background tasks. The IHostedService interface in ASP.Net Core provides a simple way to implement services that execute in the background. In this post we will explore how we can use this interface to implement background tasks, aka “hosted services,” in ASP.Net Core.

The IHostedService interface was introduced in ASP.Net Core 2.0. Here is a look at this interface.

public interface IHostedService
    // Summary:
    //     Triggered when the application host is ready to start the service.
    Task StartAsync(CancellationToken cancellationToken);
    // Summary:
    //     Triggered when the application host is performing a graceful shutdown.
    Task StopAsync(CancellationToken cancellationToken);

Implement the IHostedService interface 

When implementing the IHostedService interface, we will have to implement two methods in our code. These include the StartAsync() and StopAsync() methods; the former is called at startup, the latter is called at shutdown. Note that the implementations will vary depending on the background processing we want to execute.