22 Building background tasks and services


This chapter covers

  • Creating tasks that run in the background for your application
  • Using the generic IHost to create Windows Services and Linux daemons
  • Using Quartz.NET to run tasks on a schedule in a clustered environment

We’ve covered a lot of ground in the book so far. You’ve learned how to create page-based applications using Razor Pages and how to create APIs for mobile clients and services. You’ve seen how to add authentication and authorization to your application, how to use EF Core for storing state in the database, and how to create custom components to meet your requirements.

As well as these UI-focused apps, you may find you need to build background or batch-task services. These services aren’t meant to interact with users directly. Rather, they stay running in the background, processing items from a queue or periodically executing a long-running process.

For example, you might want to have a background service that sends email confirmations for e-commerce orders, or a batch job that calculates sales and losses for retail stores after the shops close. ASP.NET Core includes support for these background tasks by providing abstractions for running a task in the background when your application starts.

22.1 Running background tasks with IHostedService

22.1.1 Running background tasks on a timer

22.1.2 Using scoped services in background tasks

22.2 Creating headless worker services using IHost

22.2.1 Creating a worker service from a template

22.2.2 Running worker services in production

22.3 Coordinating background tasks using Quartz.NET

22.3.1 Installing Quartz.NET in an ASP.NET Core application

22.3.2 Configuring a job to run on a schedule with Quartz.NET

22.3.3 Using clustering to add redundancy to your background tasks