Introduction
Worker services in .NET Core have emerged as a powerful mechanism for building background services that run continuously and perform various tasks. This blog provides a step-by-step guide on creating worker services, delving into their evolution, and elucidating the code snippets along with the execution process.
Evolution of Worker Services
Worker services represent a continuation of the .NET Core journey, evolving from the need to run background tasks efficiently. They inherit concepts from hosted services and console applications, offering a robust solution for scenarios where continuous execution is required, such as data processing, message queue consumption, or scheduled tasks.
Step 1. Create a Worker Service
Begin by creating a new worker service project using the .NET CLI
dotnet new worker -n MyWorkerService
This command generates the basic structure for a worker's service.
Step 2. Define Worker Logic
Navigate to the generated Worker.cs file. Here, you can define the logic that your worker service will execute continuously. For example.
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
In this example, the worker logs a message every second. You can replace this logic with your specific requirements.
Step 3. Configure and Run the Worker
Navigate to the Program.cs file and configure the worker service within the CreateHostBuilder method
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
This configuration registers the worker service to be managed by the host.
Step 4. Run the Worker Service
Build and run the worker service using the following commands
dotnet build
dotnet run
The worker service will start running, and you'll see log messages being generated at the specified interval.
Step 5. Execution Process
The ExecuteAsync method within the worker service is the entry point for the continuous execution process. It runs until the cancellation token signals a shutdown request. The Task.Delay ensures the specified delay between iterations.
Schedule Runs
Understanding how to schedule tasks at specific intervals or times enhances the versatility of worker services. Follow this step-by-step guide to incorporate scheduling into your .NET Core worker service.

Join the conversation! Your thoughts help the community grow.