How to Create a Background Service for Periodic Tasks in ASP.NET Core with C#
One of the powerful features of ASP.NET Core is the ability to run background services that can perform tasks without requiring a user to interact with the application. These services can be added to your ASP.NET Core application as hosted services, and can be started and stopped as part of the application lifecycle.
In this article, we’ll take a look at how to add a BackgroundService
to your ASP.NET Core application.
Step 1: Create a Background Service
The first step in adding a BackgroundService
is to create a class that inherits from the BackgroundService
class. This class defines a ExecuteAsync
method that is called when the background service is started, and should return a Task
that represents the work being performed.
Here’s an example of a simple BackgroundService
class:
public class PeriodicHostedService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
public PeriodicHostedService (IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// All code goes here
await Task.Delay(new TimeSpan(hrs, min, 0));
}
}
}
In ASP.NET Core, IServiceProvider
is an interface that is used to resolve dependencies between different components of your application. It acts as a container for objects or services that your application needs to function, allowing them to be easily retrieved and used by other components.
By using IServiceProvider
and the dependency injection container, you can easily manage dependencies and promote loose coupling between the components of your application.
To get an instance of the database context, you can use the GetRequiredService
method of the IServiceProvider
:
var _DbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
The await Task.Delay(new TimeSpan(hrs, min, 0))
line of code in a background service on ASP.NET Core represents a delay before executing the next iteration of the background task.
await Task.Delay(new TimeSpan(hrs, min, 0));
Step 2: Register the Background Service
Once you’ve created your BackgroundService
class, the next step is to register it with the dependency injection container in your ASP.NET Core application.
To do this, you can add the following code in your Program.cs
file:
builder.Services.AddHostedService<PeriodicHostedService>();
For .Net 5 below, you can add the following code in your Startup.cs
file:
services.AddHostedService<PeriodicHostedService>();
What the complete code looks like:
public class PeriodicHostedService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
public PeriodicHostedService (IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
int min = 1;
int hrs = 0;
try
{
using (var scope = _serviceProvider.CreateScope())
{
// All you code goes here
// getting DbContext instance
var _DbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
}
}
catch (Exception ex)
{
}
finally
{
// this sets the timer
await Task.Delay(new TimeSpan(hrs, min, 0));
}
}
}
}
Conclusion
Adding a BackgroundService
to your ASP.NET Core application can be a powerful way to perform long-running background tasks and keep your application running smoothly. By following the steps outlined in this article, you can add a simple background service to your ASP.NET Core application in just a few easy steps.