all Python 3timeterm
sched.scheduler
event scheduler
A simple event scheduler: it calls functions after a delay or at a given time, ordered by time and priority.
Syntax
s = sched.scheduler(timefunc=time.monotonic, delayfunc=time.sleep)
run() blocks the thread until the queue is empty — it is not a background timer; for background work use threading.Timer or asyncio. Events do not repeat: a periodic task must reschedule itself. Priority (lower runs first) matters only for equal times, and two enter() calls with the same delay get different times — use enterabs with a shared moment for priority to apply. Arguments are passed as a tuple — ('a',) with the comma. An exception in an action propagates out of run(), and the remaining events stay queued.
Examples
import sched, time
s = sched.scheduler(time.monotonic, time.sleep)
log = []
now = time.monotonic()
s.enterabs(now + 0.02, 1, log.append, ('b',))
s.enterabs(now + 0.01, 1, log.append, ('a',))
s.enterabs(now + 0.01, 0, log.append, ('first',)) # то же время, приоритет выше
s.run() # блокирует, пока очередь не опустеет
print(log) # → ['first', 'a', 'b']
import sched
s = sched.scheduler()
event = s.enter(10, 1, print, ('never',))
print(s.empty()) # → False
s.cancel(event)
print(s.empty()) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy