Running automatic tasks in .NET Core WebAPI

Nitesh Singhal
2 min readSep 3, 2021

--

Recently in one of the discussion for our WebAPI project we got into a scenario where we were suppose to update some value automatically without being triggered by any API.

The discussion left me wondering if this is possible in WebAPI project, so I decided to do some search and finally found a way of doing this by using background service in ASP.Net core WebAPI.

IHostedService and BackgroundService

In ASP.Net core, we can implement IHostedService interface to run background tasks asynchronously inside our application.

It provides to two methods “StartAsync” and “StopAsync”. as the name suggested these methods is used to start and stop the task.

ASP.Net core also provides abstract class “BackgroundService” which exposes only one method “ExecuteAsync” which executes continuously in background.

We can write our logic inside this methods so that it get executed in background.

In this tutorial I am going to show demo of backgroundservice implementation.

So let’s get started..

Sample example

Let’s take an example that I want to take backup of data at midnight.

Let’s see how we can achieve this with background service.

Create a new webapi project with visual studio and add the following class.

Now open Program.cs and add the following code to CreateHostBuilder method.

For .NET 5 and below

...
.ConfigureServices(services =>
{
services.AddHostedService<WorkerService>();
});

For .NET 6 and above

builder.Services.AddHostedService<WorkerService>();

Build the project and run.

You will see the task getting executed without any external trigger from any API.

Console window showing execution of background task

Summary

Background task will be required for many use cases like if you want to take backup or trigger a specific task at certain time or if you want to refresh cache or something else.

For simple background task you can use this technique, but for more complex scenarios you can make use of libraries like Quartz and Hangfire where task management is easy.

Hope this is useful.

Let me know your thoughts below..!

--

--

Nitesh Singhal

Software architect, Exploring ASP.Net core and containerization technologies