IC Improve Code Recipes

Recipe 14.2 · Python

Running at a Time of Day

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

The 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 night the clocks go back.

The way it's often written

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

If RunBilling takes less than a minute, it runs twice within the 2:00 minute. If the check happens at 1:59:59.9 and then again at 2:01:00.1, it doesn't run at all. DateTime.Now is the server's local time, which on a cloud VM is usually UTC. And on the night the clocks change, 2:00 a.m. happens twice in the autumn and not at all in the spring. DateTime.Now appears in about 19,999 hand-written C# files in the archive, across 33 engagements, and code like this is one of the reasons it matters.

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

Python Poll the local clock every minute to run billing at 02:00 (p305_r14_2_poll_clock_every_minute_before.py)
"""Poll the local clock every minute to run billing at 02:00

Source: ImproveCode, Chapter 14, Recipe 14.2 "Running at a Time of Day"
Section: The way it's often written
Book page: 305  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
DateTime.Now -> naive datetime.now() (server-local time); Thread.Sleep -> time.sleep.
"""

from __future__ import annotations

import time
from datetime import datetime


def run_billing() -> None:
    ...  # the nightly billing run


# Not to copy: misses runs, double-runs, server-local time
def billing_loop() -> None:
    while True:
        if datetime.now().hour == 2 and datetime.now().minute == 0:
            run_billing()
        time.sleep(60)

The improved recipe

Compute the next run time as an instant, wait until then, run, and repeat. Keep the calculation in its own class so the daylight-saving rules can be tested without waiting for March.

Registration, with the time zone given by its IANA name:

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

Python DST-safe daily schedule: next run of a wall-clock time in a time zone (p305_r14_2_dst_safe_daily_schedule.py)
"""DST-safe daily schedule: next run of a wall-clock time in a time zone

Source: ImproveCode, Chapter 14, Recipe 14.2 "Running at a Time of Day"
Section: The improved recipe
Book page: 305-306  -- original C# listing
Converted from C# to Python.
TimeZoneInfo -> zoneinfo.ZoneInfo; TimeOnly -> datetime.time; DateTimeOffset -> an aware
datetime with a fixed offset. IsInvalidTime is detected by a UTC round trip and
IsAmbiguousTime by comparing the offsets of fold=0 and fold=1.
"""

from __future__ import annotations

from datetime import UTC, datetime, time, timedelta, timezone
from zoneinfo import ZoneInfo


class DailySchedule:
    def __init__(self, run_at: time, zone: ZoneInfo) -> None:
        self.run_at = run_at
        self.zone = zone

    def get_next_occurrence(self, after: datetime) -> datetime:
        local_now = after.astimezone(self.zone).replace(tzinfo=None)
        candidate = datetime.combine(local_now.date(), self.run_at)
        if candidate <= local_now:
            candidate += timedelta(days=1)

        # During the repeated autumn hour, today's first 1:30 may
        # already be in the past. Never return an earlier instant.
        next_ = self._to_instant(candidate)
        return next_ if next_ > after else self._to_instant(candidate + timedelta(days=1))

    def _to_instant(self, local: datetime) -> datetime:
        # Spring forward: 2:30 does not exist, run at the first
        # valid minute after it.
        while self._is_invalid_time(local):
            local += timedelta(minutes=1)

        # Fall back: 1:30 happens twice, run at the first one.
        offset = (max(self._ambiguous_offsets(local))
                  if self._is_ambiguous_time(local)
                  else local.replace(tzinfo=self.zone).utcoffset())
        assert offset is not None

        return local.replace(tzinfo=timezone(offset))

    def _is_invalid_time(self, local: datetime) -> bool:
        aware = local.replace(tzinfo=self.zone)
        round_trip = aware.astimezone(UTC).astimezone(self.zone)
        return round_trip.replace(tzinfo=None) != local

    def _ambiguous_offsets(self, local: datetime) -> list[timedelta]:
        offsets = []
        for fold in (0, 1):
            offset = local.replace(tzinfo=self.zone, fold=fold).utcoffset()
            assert offset is not None
            offsets.append(offset)
        return offsets

    def _is_ambiguous_time(self, local: datetime) -> bool:
        first, second = self._ambiguous_offsets(local)
        return first != second and not self._is_invalid_time(local)

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

Python Background service that runs a job once a day at a scheduled time (p306_r14_2_daily_job_background_service.py)
"""Background service that runs a job once a day at a scheduled time

Source: ImproveCode, Chapter 14, Recipe 14.2 "Running at a Time of Day"
Section: The improved recipe
Book page: 306-307  -- original C# listing
Converted from C# to Python.
BackgroundService -> the asyncio stand-in from the 14.1 module; TimeProvider -> an
injectable clock callable (the delay itself uses the real event-loop clock);
Task.Delay(..., stoppingToken) -> a wait on the stopping Event.
"""

from __future__ import annotations

import asyncio
import logging
from collections.abc import Callable
from datetime import UTC, datetime

from p301_r14_1_scheduled_job_interface_options import IScheduledJob
from p302_r14_1_timed_job_background_service import BackgroundService, wait_or_stopped
from p305_r14_2_dst_safe_daily_schedule import DailySchedule


def system_clock() -> datetime:
    return datetime.now(UTC)


class DailyJobService[TJob: IScheduledJob](BackgroundService):
    def __init__(
            self,
            schedule: DailySchedule,
            job_type: type[TJob],
            scope_factory: Callable[[], TJob] | None = None,
            time: Callable[[], datetime] = system_clock,
            logger: logging.Logger | None = None) -> None:
        super().__init__()
        self._schedule = schedule
        self._job_type = job_type
        self._create_job = scope_factory or job_type
        self._time = time
        self._logger = logger or logging.getLogger(
            f"{__name__}.DailyJobService[{job_type.__name__}]")

    async def execute(self, stopping: asyncio.Event) -> None:
        name = self._job_type.__name__
        while not stopping.is_set():
            now = self._time()
            next_ = self._schedule.get_next_occurrence(now)
            self._logger.info(
                "%s next run at %s",
                name, next_.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%SZ"))

            if await wait_or_stopped(stopping, (next_ - now).total_seconds()):
                return

            try:
                await self._create_job().run(stopping)
            except Exception:
                # CancelledError is not an Exception: shutdown still propagates.
                self._logger.exception("%s failed", name)

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

Python Register a nightly billing run at 02:00 New York time (p307_r14_2_register_nightly_billing_job.py)
"""Register a nightly billing run at 02:00 New York time

Source: ImproveCode, Chapter 14, Recipe 14.2 "Running at a Time of Day"
Section: The improved recipe
Book page: 307  -- original C# listing
Converted from C# to Python.
Startup fragment wrapped in a function. FindSystemTimeZoneById -> zoneinfo.ZoneInfo
(IANA id); AddHostedService -> appending to the host's service list.
"""

from __future__ import annotations

import asyncio
import logging
from datetime import time
from zoneinfo import ZoneInfo

from p302_r14_1_timed_job_background_service import BackgroundService
from p305_r14_2_dst_safe_daily_schedule import DailySchedule
from p306_r14_2_daily_job_background_service import DailyJobService, system_clock


class NightlyBillingRun:
    """The billing job (an IScheduledJob defined elsewhere in the book)."""

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


def register_nightly_billing(services: list[BackgroundService]) -> None:
    zone = ZoneInfo("America/New_York")
    services.append(
        DailyJobService(
            DailySchedule(time(2, 0), zone),
            NightlyBillingRun,
            time=system_clock,
            logger=logging.getLogger("DailyJobService[NightlyBillingRun]")))

How it works

GetNextOccurrence converts "now" into the business time zone, builds today's run time on the wall clock, and moves to tomorrow if that time has passed. Only then does it convert back to an instant. Working on the wall clock is what keeps the job at 2:00 local time across the change from standard time to daylight time, when the UTC time of the run shifts by an hour.

ToInstant handles the two awkward nights. In spring, local times between 2:00 and 3:00 don't exist, and IsInvalidTime returns true. The loop moves forward to the first valid minute, so a 2:30 job runs at 3:00 that night instead of being skipped. In autumn, 1:00 to 2:00 happens twice, and GetAmbiguousTimeOffsets returns both offsets. The larger offset is the earlier instant, the first time the clock shows 1:30, so the job runs once. A service restarted during the repeated hour would otherwise compute an instant that has already passed, so the method moves to the next day whenever the result is not later than after.

I tested these cases for America/New_York around the 2026 changes: a 2:30 run on 8 March came out at 3:00 local (07:00 UTC), and a 1:30 run on 1 November came out at 05:30 UTC, the first occurrence, exactly once.

Task.Delay(TimeSpan, TimeProvider, CancellationToken) waits on the injected clock. In production that is TimeProvider.System. In tests, FakeTimeProvider from the Microsoft.Extensions.TimeProvider.Testing package lets you advance time by a day in a microsecond and assert that the job ran.

Variations and pitfalls

  • Store the time zone, not an offset. -05:00 is right for half the year. An IANA name such as America/New_York (supported on Windows since .NET 6) or a Windows ID such as Eastern Standard Time carries the rules.
  • Missed runs. If the server is down at 2:00, this service does not catch up when it returns. If a missed run must happen, record the last successful run date in the database and run at start-up when it is older than today.
  • Several times a day or business days only. Generalize DailySchedule to an ISchedule interface with GetNextOccurrence. For anything that reads like a cron expression, use the scheduler in Recipe 14.6 rather than writing a cron parser. Chapter 15 covers business-day calculations.