Chapter 14
Background Jobs and Scheduling
Every business system has work that nobody clicks a button for. The nightly billing run, the import that picks up a partner's file at 6 a.m., the e-mail queue, the job that purges old audit rows, the sync that pushes orders to the warehouse every five minutes. This is the code that wakes people up. It runs when nobody is watching and fails quietly, and the first sign is often a customer asking why their invoice never arrived.
Scheduling and background-job classes were one of the most common themes in my consulting
archive: 6,145 classes across 27 engagements. Most were variations on a single design: a Windows
Service, a thread started in OnStart, and a while loop with Thread.Sleep at the bottom.
About 2,290 hand-written C# files in the archive call Thread.Sleep, spread over 26 engagements.
Some of those are harmless, but many are the heartbeat of a scheduler that cannot be stopped
cleanly, cannot be tested, and drifts a little later every day.
Modern .NET has a much better foundation. The Generic Host in Microsoft.Extensions.Hosting gives
you dependency injection, configuration, logging and a managed lifetime for long-running work.
BackgroundService and PeriodicTimer replace the sleep loop. Microsoft.Extensions.Hosting.WindowsServices
turns the same program into a Windows Service. System.Threading.Channels gives you an in-process
queue that is fast and safe. This chapter shows how to use them together, how to shut down without
losing work, and when to stop writing your own scheduler and use Quartz.NET or Hangfire instead.
Recipes
- 14.1Replacing the Thread.Sleep Loop With BackgroundServiceA Windows Service runs a sync every five minutes. Stopping it takes minutes or fails with "the service did not respond to the stop request in a…
- 14.2Running at a Time of DayThe billing job must run at 2:00 a.m. Eastern time every day. Not every 24 hours from whenever the service was last restarted, and not twice on the…
- 14.3Running as a Windows ServiceThe job must run on a Windows server, start at boot, run under a low-privilege account and restart if it fails. The old way meant a ServiceBase…
- 14.4In-Process Queues With System.Threading.ChannelsA web request needs to start work that takes longer than the user should wait: sending a receipt e-mail, generating a PDF, calling a slow partner.…
- 14.5Graceful ShutdownA deployment restarts the service in the middle of an import. Half the batch is committed, the other half is lost, and the file is marked as…
- 14.6When to Reach for Quartz.NET or HangfireThe schedule list grows: billing at 2:00 on weekdays, a report at 6:00 on the first business day of the month, an archive job every Sunday. Jobs must…
Chapter checklist
- Search for
Thread.Sleepin services and replace each sleep loop with aBackgroundServiceand aPeriodicTimeror a cancellableTask.Delay. - Split every job into a plain class with
RunAsync(CancellationToken)and run it in a fresh dependency-injection scope. - Compute time-of-day schedules in a named time zone, and test the two daylight-saving nights.
- Host Windows Services with
AddWindowsService, run them as a virtual account, and set recovery actions. - Replace fire-and-forget
Task.Runcalls with a bounded channel and a fixed number of workers. - Pick a safe stopping point for each job, check the token only there, and set
ShutdownTimeoutlonger than one unit of work. - Move to Quartz.NET or Hangfire before your own scheduler grows a cron parser or a jobs table.