12.2 The sched Module

The sched module supplies a class that implements an event scheduler. sched supplies a scheduler class.

scheduler

class scheduler(timefunc,delayfunc)

An instance s of scheduler is initialized with two functions, which s then uses for all time-related operations. timefunc must be callable without arguments to get the current time instant (in any unit of measure), meaning that you can pass time.time. delayfunc must be callable with one argument (a time duration, in the same units timefunc returns), and it should delay for about that amount of time, meaning you can pass time.sleep. scheduler also calls delayfunc with argument 0 after each event, to give other threads a chance; again, this is compatible with the behavior of time.sleep.

A scheduler instance s supplies the following methods.

cancel

s.cancel(event_token)

Removes an event from s's queue of scheduled events. event_token must be the result of a previous call to s.enter or s.enterabs, and the event must not yet have happened; otherwise cancel raises RuntimeError.

empty

s.empty(  )

Returns True if s's queue of scheduled events is empty, otherwise False.

enterabs

s.enterabs(when,priority,func,args)

Schedules a future event (i.e., a callback to func(*args)) at time when. when is expressed in the same units of measure used by the time functions of s. If several events are scheduled for the same instant, s executes them in increasing order of priority. enterabs returns an event token t, which you may later pass to s.cancel to cancel this event.

enter

s.enter(delay,priority,func,args)

Like enterabs, except that argument delay is a relative time (the difference from the current instant, in the same units of measure), while enterabs's argument when is an absolute time (a future instant).

run

s.run(  )

Runs all scheduled events. s.run loops until s.empty( ), using delayfunc as passed on s's initialization to wait for the next scheduled event, and then executes the event. If a callback func raises an exception, s propagates it, but s keeps its own state, removing from the schedule the event whose callback raised. If a callback func takes longer to run than the time available before the next scheduled event, s falls behind, but keeps executing scheduled events in order and never drops events. You can call s.cancel to drop an event explicitly if that event is no longer of interest.



    Part III: Python Library and Extension Modules