sched
sched模块定义了一个类,他用来调度事件。
class sched.scheduler(timefunc, delayfunc)
scheduler类定义了一个普通的接口用来调度事件,它实际上需要两个功能:timefunc被无参数调用,并返回一个数值。delayfunc使用一个参数调用。
scheduler实例含有以下方法和属性:
scheduler.enterabs(time, priority, action, argument)
调度一个新事件,time参数应该是数值类型的。
scheduler.enter(delay, priority, action, argument)
延迟调度一个事件,不同于相对时间
scheduler.cancel(event)
在事件队列中移除一个事件,如果事件不在事件队列中,则触发ValueError
scheduler.empty()
如果事件队列为空则返回True
scheduler.run()
运行所有的调度事件,该函数会等待下一个事件,然后执行他直到没有可调度的事件为止。
scheduler.queue
只读属性,返回一个list,里面包含了即将运行的事件列表。
In multi-threaded environments, the scheduler class has limitations with respect to thread-safety, inability to insert a new task before the one currently pending in a running scheduler, and holding up the main thread until the event queue is empty. Instead, the preferred approach is to use the threading.Timer class instead.
下面举个简单的例子:
#!/usr/bin/python
import sched,time
s=sched.scheduler(time.time,time.sleep)
def print_time():
print 'from print_time',time.time()
def print_some_time():
print time.time()
s.enter(10,1,print_time,())
s.enter(20,1,print_time,())
#print s.queue
s.run()
print time.time()
print_some_time()