Python Sched Module
The sched module defines a class which implements a general purpose event scheduler.
Importing the Module
import sched
import time
Creating a Scheduler
To create a scheduler, you instantiate the scheduler class. It takes two arguments: a function to return the current time, and a function to delay execution.
s = sched.scheduler(time.time, time.sleep)
Scheduling Events
enter()
Schedule an event to be executed after a delay.
def print_event(name):
print('EVENT:', time.time(), name)
print('START:', time.time())
s.enter(2, 1, print_event, argument=('first',))
s.enter(3, 1, print_event, argument=('second',))
enterabs()
Schedule an event to be executed at a specific time.
# Schedule at a specific time (e.g., current time + 5 seconds)
s.enterabs(time.time() + 5, 1, print_event, argument=('third',))
Running the Scheduler
The run() method blocks until all scheduled events have been executed.
s.run()
Canceling Events
Events can be canceled using cancel(). enter() returns an event object which can be used for cancellation.
e = s.enter(10, 1, print_event, argument=('canceled',))
s.cancel(e)