sched
— 事件调度器
¶
源代码: Lib/sched.py
The
sched
模块定义实现一般目的的事件调度器类:
sched.
scheduler
(
timefunc=time.monotonic
,
delayfunc=time.sleep
)
¶
The
scheduler
类定义调度事件的一般接口。它需要 2 个函数以实际处理外部世界 —
timefunc
should be callable without arguments, and return a number (the “time”, in any units whatsoever). If time.monotonic is not available, the
timefunc
default is time.time instead. The
delayfunc
函数应该是带有一自变量的可调用,兼容其输出为
timefunc
,且应该延迟多个时间单位。
delayfunc
还将被调用采用自变量
0
在每个事件运行后,允许其它线程有机会在多线程应用程序中运行。
3.3 版改变: timefunc and delayfunc 参数是可选的。
3.3 版改变:
scheduler
类可以安全地用于多线程环境。
范例:
>>> import sched, time >>> s = sched.scheduler(time.time, time.sleep) >>> def print_time(a='default'): ... print("From print_time", time.time(), a) ... >>> def print_some_times(): ... print(time.time()) ... s.enter(10, 1, print_time) ... s.enter(5, 2, print_time, argument=('positional',)) ... s.enter(5, 1, print_time, kwargs={'a': 'keyword'}) ... s.run() ... print(time.time()) ... >>> print_some_times() 930343690.257 From print_time 930343695.274 positional From print_time 930343695.275 keyword From print_time 930343700.273 default 930343700.276
scheduler
实例拥有下列方法和属性:
scheduler.
enterabs
(
time
,
priority
,
action
,
argument=()
,
kwargs={}
)
¶
调度新的事件。 time 自变量应该是数值类型兼容返回值对于 timefunc 函数被传递给构造函数。事件调度为相同 time 将执行他们按其次序如 priority .
执行事件意味着执行
action(*argument, **kwargs)
.
argument
是保持位置自变量的序列对于
action
.
kwargs
是保持关键词自变量的字典对于
action
.
返回值是事件,可以用于稍后消除事件 (见
cancel()
).
3.3 版改变: argument 参数是可选的。
3.3 版新增: kwargs 参数被添加。
scheduler.
enter
(
delay
,
priority
,
action
,
argument=()
,
kwargs={}
)
¶
调度事件为
delay
更多时间单位。除相对时间外,其它自变量、作用和返回值相同如那些在
enterabs()
.
3.3 版改变: argument 参数是可选的。
3.3 版新增: kwargs 参数被添加。
scheduler.
cancel
(
event
)
¶
从队列移除事件。若
event
不是目前队列中的事件,此方法将引发
ValueError
.
scheduler.
empty
(
)
¶
Return true if the event queue is empty.
scheduler.
run
(
blocking=True
)
¶
运行所有调度事件。此方法将等待 (使用
delayfunc()
function passed to the constructor) for the next event, then execute it and so on until there are no more scheduled events.
若 blocking is false executes the scheduled events due to expire soonest (if any) and then return the deadline of the next scheduled call in the scheduler (if any).
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.
3.3 版新增: blocking 参数被添加。