Worker service
A worker service is a .NET app with a host but no web server: the natural home for jobs that should
run apart from the processes that serve requests. The host starts the scheduler, and stops it on
SIGTERM or Ctrl+C.
Create it
Section titled “Create it”Delete the Worker.cs the template made; the scheduler takes its place.
Program.cs
Section titled “Program.cs”The jobs
Section titled “The jobs”Each run gets a new service scope and a new ReportJobs from it, so the class can take scoped
services. Attributes lists every property.
Configuration
Section titled “Configuration”The connection string comes from configuration, so it never sits in code:
In production, set it from the environment (ConnectionStrings__redis) or a secret store. At the
Debug level the scheduler logs every run it starts and finishes; at Information it logs only
what goes wrong.
Run several
Section titled “Run several”Start the worker in three terminals. Every scheduled time runs on one of them; stop one with Ctrl+C and the others carry on. On a lease backend, a job that was running is handed over within two heartbeats.
Stopping
Section titled “Stopping”The host stops the scheduler when it receives SIGTERM (Docker, Kubernetes, systemd) or Ctrl+C:
- Running jobs see
ctx.CancellationTokencancelled. - A job that throws then is handed over to another instance at once.
- The host waits up to
StopTimeout(30 seconds), and no longer than its ownShutdownTimeout.
Jobs that pass the token on to every call they make stop in time. See Writing handlers and Long-running jobs.
In a container
Section titled “In a container”ENTRYPOINT in this form makes dotnet the process that receives SIGTERM. Give each container
its name as InstanceId, so history shows which one ran each run:
As a systemd service
Section titled “As a systemd service”systemctl stop then sends SIGTERM and waits for the host. Keep TimeoutStopSec above
StopTimeout.
Run the example
Section titled “Run the example”The Hosting example is
this worker:
- ASP.NET Core: jobs in a web app, with endpoints
- Rolling deploys on Kubernetes
- Hosting reference