Doing Background Work with a Hosted Service in Web API

This is one of those posts where I wanted to do something simple but couldn’t find the documentation for it. I wanted to create a simple Web API that would run a background task every 2 seconds. I wanted to use a HostedService to do this.

There are plenty of examples of how to use hosted services in Worker projects, but I couldn’t find one for a Web API. In the end, it was very easy and worked the way you might expect, but it took me more than ten minutes to figure it out, so it’s worth writing down for others. And, yes, I generally would not advise running a background task in a Web API, but this is just an example.

My hosted service is very simple. It just writes to the console every 2 seconds. Here is the code:

 1public sealed class Worker() : BackgroundService
 3    int loop = 0;
 4    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 5    {
 6        while (!stoppingToken.IsCancellationRequested)
 7        {
 8            Console.WriteLine($"Worker called {++loop} times. {DateTime.Now}");
 9            await Task.Delay(2000, stoppingToken);
10        }
11    }

Then in my Program.cs file, I add the hosted service to the service collection:

1var builder = WebApplication.CreateBuilder(args);
3// Add services to the container.
5var app = builder.Build();
6// snip...

When the application runs, I can hit my endpoints and see the console output every 2 seconds.

Worker called 1 times. 8:55:15 PM
Worker called 2 times. 8:55:17 PM
Worker called 3 times. 8:55:19 PM
Worker called 4 times. 8:55:21 PM

That’s all there is to it.

comments powered by Disqus