On this page
  1. sched
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Discrete-Event Simulation with a Virtual Clock
  7. 2. Canceling Scheduled Events
  8. Gotchas & Boundaries
  9. Classes & Objects

sched

Prev: runpy | Up: stdlib_module | Next: secrets
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — sched
Tags: #public #python3 #stdlib


Import

import sched

Overview

General-purpose, single-threaded event scheduler (sched.scheduler) that executes callables at specified relative delays (enter()) or absolute timestamps (enterabs()). Use sched for lightweight, dependency-free in-process timers or discrete-event simulations (by swapping in a virtual clock function).

Quick Start

import sched
import time

s = sched.scheduler(time.monotonic, time.sleep)
events: list[str] = []

s.enter(0.01, priority=1, action=events.append, argument=("first",))
s.enter(0.02, priority=1, action=events.append, argument=("second",))
s.run()

assert events == ["first", "second"]

Implementation Walkthrough

1. Discrete-Event Simulation with a Virtual Clock

Because sched.scheduler accepts custom timefunc and delayfunc callables, you can simulate hours of scheduled events instantaneously without sleeping:

import sched

clock = 0.0
log: list[tuple[float, str]] = []

def fake_time() -> float:
    return clock

def fake_sleep(dt: float) -> None:
    global clock
    clock += dt

sim = sched.scheduler(fake_time, fake_sleep)
sim.enter(60.0, 1, lambda: log.append((clock, "1m")))
sim.enter(300.0, 1, lambda: log.append((clock, "5m")))
sim.run()

assert log == [(60.0, "1m"), (300.0, "5m")]

2. Canceling Scheduled Events

enter() and enterabs() return an Event token that can be removed before it fires with s.cancel(event).

Gotchas & Boundaries

Classes & Objects

Linked from

Related notes