源代码: Lib/sched.py
The sched 模块定义实现一般目的的事件调度器类:
The scheduler 类定义调度事件的一般接口。它需要 2 个函数以实际处理外部世界 — timefunc 应该是不带自变量的可调用,并返回数字 (时间,无论按任何单位)。 delayfunc 函数应该是带有一自变量的可调用,兼容其输出为 timefunc ,且应该延迟多个时间单位。 delayfunc 还将被调用采用自变量 0 在每个事件运行后,允许其它线程有机会在多线程应用程序中运行。
范例:
>>> import sched, time >>> s = sched.scheduler(time.time, time.sleep) >>> def print_time(): print "From print_time", time.time() ... >>> def print_some_times(): ... print time.time() ... s.enter(5, 1, print_time, ()) ... s.enter(10, 1, print_time, ()) ... s.run() ... print time.time() ... >>> print_some_times() 930343690.257 From print_time 930343695.274 From print_time 930343700.273 930343700.276
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 类代替。
范例:
>>> import time >>> from threading import Timer >>> def print_time(): ... print "From print_time", time.time() ... >>> def print_some_times(): ... print time.time() ... Timer(5, print_time, ()).start() ... Timer(10, print_time, ()).start() ... time.sleep(11) # sleep while time-delay events execute ... print time.time() ... >>> print_some_times() 930343690.257 From print_time 930343695.274 From print_time 930343700.273 930343701.301
scheduler 实例拥有下列方法和属性:
调度新的事件。 time 自变量应该是数值类型兼容返回值对于 timefunc 函数被传递给构造函数。事件调度为相同 time 将执行他们按其次序如 priority .
执行事件意味着执行 action(*argument) . argument must be a sequence holding the parameters for action .
返回值是事件,可以用于稍后消除事件 (见 cancel() ).
调度事件为 delay 更多时间单位。除相对时间外,其它自变量、作用和返回值相同如那些在 enterabs() .
从队列移除事件。若 event 不是目前队列中的事件,此方法将引发 ValueError .
Return true if the event queue is empty.
Run all scheduled events. This function will wait (using the delayfunc() function passed to the constructor) for the next event, then execute it and so on until there are no more scheduled events.
Either action or delayfunc can raise an exception. In either case, the scheduler will maintain a consistent state and propagate the exception. If an exception is raised by action , the event will not be attempted in future calls to run() .
If a sequence of events takes longer to run than the time available before the next event, the scheduler will simply fall behind. No events will be dropped; the calling code is responsible for canceling events which are no longer pertinent.