IC Improve Code Recipes

Recipe 14.6 · Python

When to Reach for Quartz.NET or Hangfire

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 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 not run twice when the service runs on two servers. Operations want to see what ran, what failed, and to rerun a failed job without a deployment. The hosted services from this chapter can do some of this, but you would be writing a scheduler.

The way it's often written

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

I have inherited more than one of these: a JobScheduler class, a ScheduledJobs table, and years of patches for daylight saving time, months with 30 days and locks that were never released after a crash.

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

Python Hand-written frequency scheduler with if/else rules (p320_r14_6_hand_written_scheduler_before.py)
"""Hand-written frequency scheduler with if/else rules

Source: ImproveCode, Chapter 14, Recipe 14.6 "When to Reach for Quartz.NET or Hangfire"
Section: The way it's often written
Book page: 320  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
The fragment is wrapped in a function; DayOfWeek -> datetime.weekday() (Monday=0).
"""

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime


@dataclass
class ScheduledJob:
    frequency: str
    hour: int
    day: int
    day_of_month: int


def run(job: ScheduledJob) -> None:
    ...


def run_if_due(job: ScheduledJob, now: datetime) -> None:
    # Not to copy: a hand-written scheduler that grew a table and a parser
    if job.frequency == "Daily" and now.hour == job.hour: run(job)
    elif job.frequency == "Weekly" and now.weekday() == job.day: run(job)
    elif job.frequency == "Monthly" and now.day == job.day_of_month: run(job)
    # ...plus a ScheduledJob table, a LastRun column and a lock flag

The improved recipe

Use a library once the requirements pass a simple interval or a single daily time. This table is how I decide:

Requirement Reach for
Fixed interval, one instance TimedJobService (14.1)
One time of day DailyJobService (14.2)
Fire-and-forget, loss is acceptable Channels (14.4)
Cron schedules, calendars, clustering Quartz.NET
Durable queued jobs, retries, dashboard Hangfire

Quartz.NET 3.x, from the Quartz.Extensions.Hosting package, runs cron-style schedules in the Generic Host. (Quartz.NET 4 targets .NET 10 and moves these APIs into the main Quartz package.) A small adapter lets the IScheduledJob classes from this chapter run under Quartz without changes:

Hangfire, from the Hangfire.AspNetCore and Hangfire.SqlServer packages, stores every job in the database, so jobs survive restarts and failures are retried automatically:

Requirements: Python 3.12+. Install: pip install apscheduler

Python Schedule the invoice sync job at 02:00 on weekdays (p321_r14_6_add_scheduled_jobs_setup.py)
"""Schedule the invoice sync job at 02:00 on weekdays

Source: ImproveCode, Chapter 14, Recipe 14.6 "When to Reach for Quartz.NET or Hangfire"
Section: The improved recipe
Book page: 321-322  -- original C# listing
Converted from C# to Python.
AddQuartz -> an APScheduler AsyncIOScheduler; AddQuartzHostedService with
WaitForJobsToComplete -> a BackgroundService (14.1 stand-in) that starts the scheduler
and, on stop, shuts it down and awaits the in-flight runs.
"""

from __future__ import annotations

import asyncio
from zoneinfo import ZoneInfo

from apscheduler.schedulers.asyncio import AsyncIOScheduler

from p302_r14_1_timed_job_background_service import BackgroundService
from p303_r14_1_invoice_sync_job import InvoiceSyncJob
from p321_r14_6_cron_job_adapter_extension import RUNNING, add_cron_job


class SchedulerHostedService(BackgroundService):
    def __init__(self, scheduler: AsyncIOScheduler, wait_for_jobs_to_complete: bool) -> None:
        super().__init__()
        self._scheduler = scheduler
        self._wait_for_jobs = wait_for_jobs_to_complete

    async def execute(self, stopping: asyncio.Event) -> None:
        self._scheduler.start()
        await stopping.wait()
        self._scheduler.shutdown(wait=False)
        if self._wait_for_jobs and RUNNING:
            await asyncio.gather(*RUNNING, return_exceptions=True)


def add_scheduled_jobs(
        services: list[BackgroundService], zone: ZoneInfo) -> AsyncIOScheduler:
    scheduler = AsyncIOScheduler(timezone=zone)
    # Seconds, minutes, hours, day of month, month, weekday.
    add_cron_job(scheduler, InvoiceSyncJob, "0 0 2 ? * MON-FRI", zone)

    services.append(SchedulerHostedService(scheduler, wait_for_jobs_to_complete=True))
    return scheduler

Requirements: Python 3.12+. Install: pip install apscheduler

Python Adapter and helper that schedule an IScheduledJob on a cron expression (p321_r14_6_cron_job_adapter_extension.py)
"""Adapter and helper that schedule an IScheduledJob on a cron expression

Source: ImproveCode, Chapter 14, Recipe 14.6 "When to Reach for Quartz.NET or Hangfire"
Section: The improved recipe
Book page: 321  -- original C# listing
Converted from C# to Python.
Quartz.NET -> APScheduler 3.x (AsyncIOScheduler + CronTrigger). [DisallowConcurrentExecution]
-> max_instances=1; misfire "fire and proceed" -> coalesce=True, misfire_grace_time=None.
The Quartz-style cron (seconds first, '?') is converted to CronTrigger fields.
"""

from __future__ import annotations

import asyncio
from collections.abc import Callable
from zoneinfo import ZoneInfo

from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger

from p301_r14_1_scheduled_job_interface_options import IScheduledJob

# In-flight runs, so a host can wait for them (WaitForJobsToComplete).
RUNNING: set[asyncio.Task[None]] = set()


class SchedulerJobAdapter[TJob: IScheduledJob]:
    def __init__(
            self,
            job_factory: Callable[[], TJob],
            stopping: asyncio.Event | None = None) -> None:
        self._job_factory = job_factory
        self._stopping = stopping or asyncio.Event()

    async def execute(self) -> None:
        task = asyncio.current_task()
        assert task is not None
        RUNNING.add(task)
        try:
            await self._job_factory().run(self._stopping)
        finally:
            RUNNING.discard(task)


def quartz_cron_trigger(cron_expression: str, zone: ZoneInfo) -> CronTrigger:
    """Seconds, minutes, hours, day of month, month, weekday [, year]."""
    parts = [p.replace("?", "*") for p in cron_expression.split()]
    if len(parts) not in (6, 7):
        raise ValueError(f"Not a Quartz cron expression: {cron_expression!r}")
    second, minute, hour, day, month, day_of_week = parts[:6]
    if any(ch.isdigit() for ch in day_of_week):
        raise ValueError("Use weekday names (Quartz and APScheduler number days differently).")
    return CronTrigger(
        second=second, minute=minute, hour=hour, day=day, month=month,
        day_of_week=day_of_week.lower(),
        year=parts[6] if len(parts) == 7 else None,
        timezone=zone)


def add_cron_job[TJob: IScheduledJob](
        scheduler: AsyncIOScheduler,
        job_type: type[TJob],
        cron_expression: str,
        zone: ZoneInfo,
        job_factory: Callable[[], TJob] | None = None,
        stopping: asyncio.Event | None = None) -> AsyncIOScheduler:
    key = job_type.__name__
    adapter = SchedulerJobAdapter(job_factory or job_type, stopping)
    scheduler.add_job(
        adapter.execute,
        trigger=quartz_cron_trigger(cron_expression, zone),
        id=key,
        name=key + "-trigger",
        max_instances=1,
        coalesce=True,
        misfire_grace_time=None,
        replace_existing=True)
    return scheduler

Requirements: Python 3.12+. Install: pip install apscheduler

Python Durable recurring and fire-and-forget jobs stored in SQL Server (p322_r14_6_durable_sql_job_store_setup.py)
"""Durable recurring and fire-and-forget jobs stored in SQL Server

Source: ImproveCode, Chapter 14, Recipe 14.6 "When to Reach for Quartz.NET or Hangfire"
Section: The improved recipe
Book page: 322  -- original C# listing
Converted from C# to Python.
Hangfire with SQL Server storage -> APScheduler with a SQLAlchemyJobStore (connection
string as an mssql+pyodbc URL); AddOrUpdate -> add_job(id=..., replace_existing=True);
Enqueue -> add_job with no trigger (run now). Jobs are stored as a module:function
reference, so the job entry point is a top-level function. Hangfire's automatic retries
and dashboard have no equivalent here.
"""

from __future__ import annotations

import asyncio
from zoneinfo import ZoneInfo

from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger

from p303_r14_1_invoice_sync_job import InvoiceSyncJob


async def run_invoice_sync() -> None:
    # A fresh job per run; asyncio.Event() never set == CancellationToken.None.
    await InvoiceSyncJob().run(asyncio.Event())


def add_durable_jobs(connection_string: str) -> AsyncIOScheduler:
    # e.g. "mssql+pyodbc://@server/db?driver=ODBC+Driver+18+for+SQL+Server"
    scheduler = AsyncIOScheduler(
        jobstores={"default": SQLAlchemyJobStore(url=connection_string)})
    # The server part (AddHangfireServer): the host calls scheduler.start().
    return scheduler


def register_recurring_jobs(jobs: AsyncIOScheduler, zone: ZoneInfo) -> None:
    jobs.add_job(
        run_invoice_sync,
        # "0 2 * * 1-5" -- weekday names avoid APScheduler's Monday=0 numbering.
        trigger=CronTrigger(minute=0, hour=2, day_of_week="mon-fri", timezone=zone),
        id="invoice-sync",
        replace_existing=True)


def enqueue_sync(client: AsyncIOScheduler) -> str:
    return client.add_job(run_invoice_sync).id

How it works

Quartz.NET is a scheduler. Its cron expressions have a seconds field, so 0 0 2 ? * MON-FRI is 2:00:00 on weekdays, and InTimeZone evaluates them in the business time zone with the daylight-saving handling built in. [DisallowConcurrentExecution] stops a slow run from overlapping the next one. The misfire instruction says what to do with a run that was missed while the service was down: fire once now and continue. WaitForJobsToComplete makes Quartz take part in graceful shutdown. By default Quartz keeps its schedule in memory. Switch to its ADO.NET job store with clustering enabled and several servers share the schedule, with each run executed by exactly one of them. Without a clustered scheduler, two servers running the same hosted service run every job twice; sp_getapplock in SQL Server is the lightweight guard.

The adapter is the reusable part. Jobs stay plain IScheduledJob classes, testable on their own, and the decision between TimedJobService and Quartz becomes one line of registration.

Hangfire is a durable job queue with a scheduler on top. Enqueue writes the job to SQL Server and returns at once, and any server running AddHangfireServer picks it up. Failed jobs are retried with increasing delays, ten times by default. Recurring jobs use standard five-field cron. The CancellationToken.None in the expression is a placeholder: Hangfire replaces it with a token that is cancelled at shutdown. Its dashboard, mapped with app.UseHangfireDashboard() in ASP.NET Core, shows queued, running, failed and succeeded jobs, and lets an operator retry one with a click.

Variations and pitfalls

  • Hangfire serializes the call, not the object. The expression is stored as the type, method and arguments. Pass IDs, not entities, and keep job method signatures stable, or queued jobs fail after a deployment that changed them.
  • Secure the dashboard. By default it is only available to local requests. Before exposing it, add an IDashboardAuthorizationFilter that checks your application's roles.
  • Licensing. Quartz.NET is Apache 2.0. Hangfire's core is LGPL with a commercial Pro edition for features such as batches.
  • Keep the job code independent. Whichever you choose, the job classes should not reference Quartz or Hangfire types. Then changing schedulers later is a registration change, not a rewrite.