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.

PythonResilience

Code

pythonsnippet
30 lines
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: sched is 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

FAQ

Are there third-party dependencies?
`sched` — install it with the package manager before running.