Run background task in asp.net core using Hosted Services Back
Run background task in asp.net core using Hosted Services
Posted on 14/11/2020 under tech .net

One of the things I loved most about .net core is you can easily implement and run background task in an asp.net core project. Background task are important particularly in microservices, where usually you would need to implement a messaging services such as RabbitMQ to listen and consume messages on a message queue.
There isn't alot of resources out there on how to implement a background task in an asp.net core app the simple way. In this blog post I'll be writing a simple example to explain how to do it.
You can refer to the source code here
Create a new asp.net core web application, it can be either mvc or api project.
Create a class, name it HelloWorldHostedService. This class will implements IHostedService. Add the following code in the class.
public class HelloWorldHostedService : IHostedService
{
private Timer _timer;
// run the logic on start
public Task StartAsync(CancellationToken cancellationToken)
{
// Register the timer task that runs in the background
RegisterTimerTask();
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
Debug.WriteLine($"Stopping task..");
return Task.CompletedTask;
}
private void RegisterTimerTask()
{
// Call helloworld every 5 seconds in background
_timer = new Timer(HelloWorld, null, 0, 5000);
}
void HelloWorld(object state)
{
Debug.WriteLine($"{DateTime.Now}");
Debug.WriteLine("Hello World !");
Debug.WriteLine("This is a hosted service");
}
}
The IHostedService interface implements StartAsync() and StopAsync() functions. So we are trying to do here is to implement a timer that runs the HelloWorld() method every 5 seconds. In StartAsync(), we will call the RegisterTimerTask() to instantiate the timer object.
Now in your project startup.cs file, register the HostedService
// Register the hosted service
services.AddHostedService<HelloWorldHostedService>();
Run your app. In the debug output window of visual studio, you will see the background task is running prints the HelloWorld message.
Another alternative way is to use BackgroundService interface. Here's an example.
public class HelloWorldBackgroundService : BackgroundService
{
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
Debug.WriteLine("Background service running !! Hello !");
await Task.Delay(8000, stoppingToken);
}
}
Remember to register the service in your startup.cs as well.
// Register the background service
services.AddHostedService<HelloWorldBackgroundService>();
This is how simple you create a background task for your app. Just create a class that implements IHostedService or BackgroundService, code your implementation and register your service in startup.