Python多线程2:sched

sched模块提供了一个类的事件安排。

scheduler类定义

class sched.scheduler(timefunc=time.monotonic, delayfunc=time.sleep) 
scheduler类为事件调度定义了一套通用接口。

它须要传入两个函数:1)timefunc是一个没有參数的callable,而且返回一个一个数字(表示“时间”,随意单位)。假设time.monotonic不是可用的,则默觉得time.time。2)delayfunc是带有一个參数的callable,与timefunc的输出兼容。用于延迟一段时间。在多线程应用中,为了给其他线程运行的机会。在每一个事件运行后,delayfunc也将使用參数0调用。


从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实例有下面方法和属性:
scheduler.enterabs(time, priority, action, argument=(), kwargs={})
调度一个新事件。time參数应该是一个数字类型。与构造器传入的timefunc函数的返回值兼容。

指定到同一个时间的事件调度将按他们的优先级顺序依次运行。
运行时间即为运行action(*argument, **kwargs)。argument是一个序列,依照action的參数顺序排列。kwargs是一个map,使用key相应action的參数。
返回值是一个事件,能够被用于事件的取消(看cancel())。


scheduler.enter(delay, priority, action, argument=(), kwargs={})
在延迟delay时间后调度一个事件。除了使用相对时间,其他的參数和返回值和enterabs是同样的。


scheduler.cancel(event)
从队列中移除事件。假设事件不在当前队列中。该方法抛出ValueError。
scheduler.empty()
假设队列是空的。则返回True。
scheduler.run(blocking=True)
运行全部的事件。这种方法将等待(使用传递给构造器的delayfunc()函数)下一个事件的时间到达,然后运行它,直到全部的事件都被运行。
假设blocking为false,则不堵塞等待,马上调度溢出时间的那些时间(假设存在),然后返回在调度器中的下次调度的须要等待的时间,比如:
>>> 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'})
        print("Next : ",s.run(False))
        print(time.time())
第一次调用:
>>> print_some_times()
1435115632.601069
Next :  5.0
1435115632.656073
Next表示下一个事件将在5秒后运行。第二次超过10秒后调用:
>>> print_some_times()
1435115665.549954
From print_time 1435115665.596957 keyword
From print_time 1435115665.607957 positional
From print_time 1435115665.618958 default
Next :  4.966997861862183
1435115665.635959
这时事件已经所有达到运行时间点。所以所有马上运行。
action后者delayfunc能抛出一个异常,这时,调度器将保持一致并传递该异常。假设异常被action抛出,以后该事件将不会再被运行。
假设一个事件运行的结束时间超过了下一个事件的运行时间,调度会忽略下一个事件。没有事件将被丢弃。
scheduler.queue
要运行的事件列表,刚看完名单,活动将在排列顺序上运行。

每个事件被存储为元组。包括:time、priority、action、argument和kwargs。

原文地址:https://www.cnblogs.com/blfshiye/p/5035644.html