时间:2022-09-20 09:27:51 | 栏目:Python代码 | 点击:次
import sched import time # 生成调度器 scheduler = sched.scheduler(time.time, time.sleep) def print_event(name): print ('EVENT:', time.time(), name) print ('START:', time.time()) # 分别设置在执行后2秒、3秒之后执行调用函数 scheduler.enter(2, 1, print_event, ('first',)) scheduler.enter(3, 1, print_event, ('second',)) # 运行调度器 scheduler.run() # 输出结果 # START: 1532050215.3737717 # EVENT: 1532050217.3747234 first # EVENT: 1532050218.375626 second
import sched import time scheduler = sched.scheduler(time.time, time.sleep) def long_event(name): print('BEGIN EVENT :', time.time(), name) time.sleep(2) print('FINISH EVENT:', time.time(), name) print('START:', time.time()) scheduler.enter(2, 1, long_event, ('first',)) # 事件无法在设想的3秒后执行,将会顺延执行 scheduler.enter(3, 1, long_event, ('second',)) scheduler.run() # 输出结果 # START: 1532051082.8237524 # BEGIN EVENT : 1532051084.8392828 first # FINISH EVENT: 1532051086.8475456 first # BEGIN EVENT : 1532051086.8475456 second # FINISH EVENT: 1532051088.8557353 second
如果多个事件是同一时间执行,通过设置他们的优先级值,用于确定顺序运行
import sched import time scheduler = sched.scheduler(time.time, time.sleep) def print_event(name): print('EVENT:', time.time(), name) now = time.time() print('START:', now) scheduler.enterabs(now+2, 2, print_event, ('first',)) scheduler.enterabs(now+2, 1, print_event, ('second',)) scheduler.run() # 输出结果 # START: 1532052567.6057265 # EVENT: 1532052569.621258 second # EVENT: 1532052569.621258 first
利用enter()和enterabs()返回一个引用事件用来取消它
import sched import threading import time scheduler = sched.scheduler(time.time, time.sleep) # 建立一个全局 线程计数器 counter = 0 def increment_counter(name): global counter print('EVENT:', time.time(), name) counter += 1 print('NOW:', counter) print('START:', time.time()) e1 = scheduler.enter(2, 1, increment_counter, ('E1',)) e2 = scheduler.enter(3, 1, increment_counter, ('E2',)) # 开始一个线程执行事件 t = threading.Thread(target=scheduler.run) t.start() # 在主线程,取消第一个预定事件 scheduler.cancel(e1) # 等待线程调度程序完成运行 t.join() # 输出结果 # START: 1532053265.5280123 # EVENT: 1532053268.528813 E2 # NOW: 1
# 判断队列是否为空 scheduler.empty() # 只读属性,返回一个即将到达的事件列表(按到达事件排序),每个事件都是有 time 、 priority 、 action 、 argument 组成的 namedtuple scheduler.queue