8.8. sched — 事件调度器

源码: Lib/sched.py


sched 模块定义了一个实现通用事件调度程序的类:

class sched.scheduler(timefunc, delayfunc)

scheduler 类定义了一个调度事件的通用接口。 它需要两个函数来实际处理“外部世界” —— 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 class instead.

示例:

>>> 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

8.8.1. 调度器对象

scheduler 实例拥有以下方法和属性:

scheduler.enterabs(time, priority, action, argument)

安排一个新事件。 time 参数应该有一个数字类型兼容的返回值,与传递给构造函数的 timefunc 函数的返回值兼容。 计划在相同 time 的事件将按其 priority 的顺序执行。 数字越小表示优先级越高。

Executing the event means executing action(*argument). argument must be a sequence holding the parameters for action.

返回值是一个事件,可用于以后取消事件( 参见 cancel() )。

scheduler.enter(delay, priority, action, argument)

安排延后 delay 时间单位的事件。 除了相对时间,其他参数、效果和返回值与 enterabs() 的相同。

scheduler.cancel(event)

从队列中删除事件。 如果 event 不是当前队列中的事件,则此方法将引发 ValueError

scheduler.empty()

Return true if the event queue is empty.

scheduler.run()

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.

actiondelayfunc 都可以引发异常。 在任何一种情况下,调度程序都将保持一致状态并传播异常。 如果 action 引发异常,则在将来调用 run() 时不会尝试该事件。

如果一系列事件的运行时间比下一个事件之前的可用时间长,那么调度程序将完全落后。 不会发生任何事件;调用代码负责取消不再相关的事件。

scheduler.queue

Read-only attribute returning a list of upcoming events in the order they will be run. Each event is shown as a named tuple with the following fields: time, priority, action, argument.

2.6 新版功能.