IC Improve Code Recipes

Recipe 14.1 · Python

Replacing the Thread.Sleep Loop With BackgroundService

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

A 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 timely fashion". An exception in the sync is swallowed or, worse, ends the thread so the service shows as running while doing nothing. Nothing in the job can be unit tested, because the database connection and the schedule are mixed in one class.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

The sleep is the core problem. Once the thread is asleep nothing can wake it, so a stop request waits for the rest of the five minutes and the Service Control Manager gives up. The _running flag is read by one thread and written by another without volatile, so the loop may never see the change. And an unhandled exception in Run ends the thread while the service stays "Running".

Requirements: Python 3.12+. Install: pip install pywin32 · Needs at run time: Windows (admin rights to install the service). The module loads without them; calling the code does not work without them.

Python Windows service with a raw thread and a five-minute sleep loop (p301_r14_1_thread_sleep_service_loop_before.py)
"""Windows service with a raw thread and a five-minute sleep loop

Source: ImproveCode, Chapter 14, Recipe 14.1 "Replacing the Thread.Sleep Loop With BackgroundService"
Section: The way it's often written
Book page: 301  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
ServiceBase -> pywin32 win32serviceutil.ServiceFramework; Thread -> threading.Thread;
Thread.Sleep -> time.sleep. SvcDoRun joins the worker, so a stop waits out the sleep.
"""

from __future__ import annotations

import threading
import time

import win32service
import win32serviceutil


class OrderSync:
    def run(self) -> None:
        ...  # the actual sync work


# Not to copy: unstoppable sleep, silent thread death, no DI
class SyncService(win32serviceutil.ServiceFramework):
    _svc_name_ = "SyncService"
    _svc_display_name_ = "Sync Service"

    def __init__(self, args: list[str]) -> None:
        super().__init__(args)
        self._worker: threading.Thread | None = None
        self._running = False

    def SvcDoRun(self) -> None:  # OnStart
        self._running = True
        self._worker = threading.Thread(target=self._loop)
        self._worker.start()
        self._worker.join()

    def SvcStop(self) -> None:  # OnStop
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self._running = False  # only seen after the current sleep ends

    def _loop(self) -> None:
        while self._running:
            OrderSync().run()  # an exception here ends the thread
            time.sleep(300)    # stop waits up to 5 minutes

The improved recipe

Separate the job from the schedule. The job is a plain class with one method. A generic hosted service runs any job on a PeriodicTimer, in its own dependency-injection scope, and logs failures without dying.

A job is now an ordinary class that can take any scoped service, such as a DbContext or a typed HTTP client from Chapter 13:

Registering it takes one line: builder.Services.AddTimedJob<InvoiceSyncJob>(TimeSpan.FromMinutes(5));

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Scheduled job contract and per-job timer options (p301_r14_1_scheduled_job_interface_options.py)
"""Scheduled job contract and per-job timer options

Source: ImproveCode, Chapter 14, Recipe 14.1 "Replacing the Thread.Sleep Loop With BackgroundService"
Section: The improved recipe
Book page: 301-302  -- original C# listing
Converted from C# to Python.
IScheduledJob -> typing.Protocol; TimedJobOptions<TJob> -> a generic dataclass.
CancellationToken -> an asyncio.Event that is set when the host is stopping.
"""

from __future__ import annotations

import asyncio
from dataclasses import dataclass
from datetime import timedelta
from typing import Protocol


class IScheduledJob(Protocol):
    async def run(self, stopping: asyncio.Event) -> None: ...


@dataclass
class TimedJobOptions[TJob: IScheduledJob]:
    interval: timedelta = timedelta(minutes=5)
    run_on_start: bool = True

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Timed background service that runs a fresh job instance per tick (p302_r14_1_timed_job_background_service.py)
"""Timed background service that runs a fresh job instance per tick

Source: ImproveCode, Chapter 14, Recipe 14.1 "Replacing the Thread.Sleep Loop With BackgroundService"
Section: The improved recipe
Book page: 302-303  -- original C# listing
Converted from C# to Python.
BackgroundService/IHost -> a minimal asyncio stand-in defined here (BackgroundService,
HostOptions, Host) and reused by the later Chapter 14 files; PeriodicTimer -> a
monotonic-deadline wait on the stopping Event; IServiceScopeFactory -> a job factory
called per run; Stopwatch -> time.perf_counter; ILogger -> logging.
"""

from __future__ import annotations

import asyncio
import contextlib
import logging
import signal
import time
from abc import ABC, abstractmethod
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from datetime import timedelta

from p301_r14_1_scheduled_job_interface_options import IScheduledJob, TimedJobOptions


# --- Minimal hosting stand-ins (Microsoft.Extensions.Hosting) -----------------

async def wait_or_stopped(stopping: asyncio.Event, seconds: float) -> bool:
    """Sleeps up to `seconds`; returns True as soon as stopping is signalled."""
    try:
        await asyncio.wait_for(stopping.wait(), max(seconds, 0.0))
        return True
    except TimeoutError:
        return False


class BackgroundService(ABC):
    def __init__(self) -> None:
        self._stopping = asyncio.Event()
        self.execute_task: asyncio.Task[None] | None = None

    @abstractmethod
    async def execute(self, stopping: asyncio.Event) -> None: ...

    async def start(self) -> None:
        self.execute_task = asyncio.create_task(
            self.execute(self._stopping), name=type(self).__name__)

    async def stop(self, timeout: float) -> None:
        """Signals stopping, waits up to `timeout`, then cancels the task."""
        self._stopping.set()
        task = self.execute_task
        if task is None:
            return
        done, _ = await asyncio.wait({task}, timeout=timeout)
        if not done:
            task.cancel()
            with contextlib.suppress(asyncio.CancelledError):
                await task


@dataclass
class HostOptions:
    shutdown_timeout: timedelta = timedelta(seconds=30)
    stop_host_on_exception: bool = True
    services_stop_concurrently: bool = False


class Host:
    def __init__(
            self,
            services: Sequence[BackgroundService],
            options: HostOptions | None = None) -> None:
        self.services = list(services)
        self.options = options or HostOptions()
        self._shutdown = asyncio.Event()

    def request_stop(self) -> None:
        self._shutdown.set()

    async def start(self) -> None:
        loop = asyncio.get_running_loop()
        for sig in (signal.SIGINT, signal.SIGTERM):
            with contextlib.suppress(NotImplementedError, RuntimeError):
                loop.add_signal_handler(sig, self.request_stop)  # not on Windows
        for service in self.services:
            await service.start()
            if self.options.stop_host_on_exception and service.execute_task:
                service.execute_task.add_done_callback(self._on_service_done)

    def _on_service_done(self, task: asyncio.Task[None]) -> None:
        if not task.cancelled() and task.exception() is not None:
            logging.getLogger(__name__).error(
                "Background service failed; stopping host",
                exc_info=task.exception())
            self.request_stop()

    async def stop(self) -> None:
        timeout = self.options.shutdown_timeout.total_seconds()
        services = list(reversed(self.services))
        if self.options.services_stop_concurrently:
            await asyncio.gather(*(s.stop(timeout) for s in services))
            return
        deadline = time.monotonic() + timeout
        for service in services:
            await service.stop(max(0.0, deadline - time.monotonic()))

    async def run(self) -> None:
        await self.start()
        try:
            await self._shutdown.wait()
        finally:
            await self.stop()


# --- The recipe ----------------------------------------------------------------

class TimedJobService[TJob: IScheduledJob](BackgroundService):
    def __init__(
            self,
            job_type: type[TJob],
            options: TimedJobOptions[TJob],
            scope_factory: Callable[[], TJob] | None = None,
            logger: logging.Logger | None = None) -> None:
        super().__init__()
        self._job_type = job_type
        self._options = options
        self._create_job = scope_factory or job_type
        self._logger = logger or logging.getLogger(
            f"{__name__}.TimedJobService[{job_type.__name__}]")

    async def execute(self, stopping: asyncio.Event) -> None:
        settings = self._options
        interval = settings.interval.total_seconds()
        next_tick = time.monotonic() + interval  # the timer starts now

        if settings.run_on_start:
            await self._run_once(stopping)

        while not await wait_or_stopped(stopping, next_tick - time.monotonic()):
            # Like PeriodicTimer, missed ticks collapse into one.
            next_tick = max(next_tick + interval, time.monotonic())
            await self._run_once(stopping)

    async def _run_once(self, stopping: asyncio.Event) -> None:
        job = self._job_type.__name__
        started = time.perf_counter()
        try:
            instance = self._create_job()  # a fresh "scope" per run
            await instance.run(stopping)

            self._logger.info(
                "%s finished in %s",
                job, timedelta(seconds=time.perf_counter() - started))
        except Exception:
            # asyncio.CancelledError is not an Exception, so a host that is
            # stopping still ends execute().
            self._logger.exception(
                "%s failed after %s",
                job, timedelta(seconds=time.perf_counter() - started))

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Register a scheduled job as a timed hosted service (p303_r14_1_add_timed_job_registration.py)
"""Register a scheduled job as a timed hosted service

Source: ImproveCode, Chapter 14, Recipe 14.1 "Replacing the Thread.Sleep Loop With BackgroundService"
Section: The improved recipe
Book page: 303  -- original C# listing
Converted from C# to Python.
AddScoped + Configure + AddHostedService -> appending a TimedJobService to the host's
service list; the job type itself is the per-run factory (scoped lifetime).
"""

from __future__ import annotations

from collections.abc import Callable
from datetime import timedelta

from p301_r14_1_scheduled_job_interface_options import IScheduledJob, TimedJobOptions
from p302_r14_1_timed_job_background_service import BackgroundService, TimedJobService


def add_timed_job[TJob: IScheduledJob](
        services: list[BackgroundService],
        job_type: type[TJob],
        interval: timedelta,
        run_on_start: bool = True,
        scope_factory: Callable[[], TJob] | None = None) -> list[BackgroundService]:
    options = TimedJobOptions[TJob](interval=interval, run_on_start=run_on_start)
    services.append(TimedJobService(job_type, options, scope_factory))
    return services

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Example scheduled job: invoice sync (p303_r14_1_invoice_sync_job.py)
"""Example scheduled job: invoice sync

Source: ImproveCode, Chapter 14, Recipe 14.1 "Replacing the Thread.Sleep Loop With BackgroundService"
Section: The improved recipe
Book page: 303-304  -- original C# listing
Converted from C# to Python.
ILogger<T> -> logging.Logger; Task.CompletedTask -> asyncio.sleep(0).
"""

from __future__ import annotations

import asyncio
import logging


class InvoiceSyncJob:
    """Implements IScheduledJob."""

    def __init__(self, logger: logging.Logger | None = None) -> None:
        self._logger = logger or logging.getLogger(f"{__name__}.InvoiceSyncJob")

    async def run(self, stopping: asyncio.Event) -> None:
        self._logger.info("Syncing invoices")
        # Load pending invoices, push them, mark them sent.
        await asyncio.sleep(0)

How it works

BackgroundService is the base class for long-running work in the Generic Host. The host calls ExecuteAsync at start-up and passes a stoppingToken that is cancelled when the application is asked to stop, whether by the Service Control Manager, Ctrl+C or a container's SIGTERM.

PeriodicTimer is the replacement for Thread.Sleep. WaitForNextTickAsync waits without blocking a thread and returns as soon as the token is cancelled. A stop request now takes milliseconds, not minutes. The timer also does not drift: ticks are scheduled from the timer's start, not from the end of the previous run. If a run takes longer than the interval, the missed tick fires once when the run finishes. Runs never overlap, and they never pile up.

Each run gets its own AsyncServiceScope. Hosted services are singletons, but the job's dependencies are often scoped, and a DbContext that lives for weeks inside a singleton is a memory leak and a stale cache. A fresh scope per run gives each run fresh dependencies, disposed at the end of the run.

The two catch blocks separate the cases that matter. Cancellation during shutdown is rethrown and ends the loop quietly. Every other exception is logged with the job name and elapsed time, and the service waits for the next tick. One bad run never ends the schedule. That is deliberate: since .NET 6, an unhandled exception in ExecuteAsync stops the whole host.

Variations and pitfalls

  • Don't block in ExecuteAsync before the first await. The host runs ExecuteAsync synchronously until it first yields. Heavy synchronous work at the top delays start-up of every other service. If the job is synchronous, start with await Task.Yield();.
  • Testing. The job class has no timer and no host, so a unit test can create it and call RunAsync directly. That alone usually justifies the split.

On .NET Framework

The Generic Host packages support .NET Framework 4.6.2 and later, so BackgroundService works in an old service project. PeriodicTimer needs .NET 6. On .NET Framework, use await Task.Delay(interval, stoppingToken) instead. It is still cancellable, which is the part that fixes the stop problem.