sched Runs Timed Events In Order
Schedule callbacks with sched.scheduler, order same-time events by priority, inspect the queue, and cancel an event before it runs.
Code
import sched
import time
def main() -> None:
scheduler = sched.scheduler(time.monotonic, time.sleep)
order: list[str] = []
def record(label: str) -> None:
order.append(label)
start = time.monotonic()
scheduler.enter(0.20, 2, record, argument=("low priority",))
scheduler.enter(0.10, 1, record, argument=("first due",))
scheduler.enter(0.10, 0, record, argument=("high priority",))
print("queued:", len(scheduler.queue))
print("next event is future:", scheduler.queue[0].time >= start)
scheduler.run()
print("order:", order)
# cancel removes a scheduled event before it runs.
handle = scheduler.enter(0.05, 1, record, argument=("cancelled",))
scheduler.cancel(handle)
print("after cancel:", len(scheduler.queue))
scheduler.run()
if __name__ == "__main__":
main()Inside the snippet
The short version: the work belongs to the functions main and record, doing all the work.
What to watch for
- Plan for an install step:
schedis a real dependency, resolved by the package manager.
Putting it to use
The demo output is labeled (queued:, next event is future:, order:), so the output doubles as a step-by-step trace of what the file did.
main is the driver: it invokes record before returning.
Core lines
def record(label: str) -> None:
order.append(label)
Interactive Tools for This Topic
Cron Expression ExplainerParse a five-field cron expression and get a field-by-field plain-English explanation plus a one-line human-readable schedule summary.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Are there third-party dependencies?
- `sched` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.