第十四章:应用构建模块-sched:定时事件调度器-取消事件

14.11.4 取消事件
enter()和enterabs()都会返回事件的一个引用,一行可以用这个引用来取消事件。由于run()会阻塞,所以必须在一个不同的线程中取消这个事件。在这个例子中,线程开始运行调度器,并用主处理线程取消事件。

import sched
import threading
import time

scheduler = sched.scheduler(time.time,time.sleep)

# Set up a global to be modified by the threads.
counter = 0


def increment_counter(name):
    global counter
    print('EVENT:',time.ctime(time.time()),name)
    counter += 1
    print('NOW:',counter)

print('START:',time.ctime(time.time()))
e1 = scheduler.enter(2,1,increment_counter,('E1',))
e2 = scheduler.enter(3,1,increment_counter,('E2',))

# Start a thread to run the events.
t = threading.Thread(target=scheduler.run)
t.start()

# Back in the main thread, cancel the first scheduled event.
scheduler.cancel(e1)

# Wait for the scheduler to finish running in the thread.
t.join()

print('FINAL:',counter)

这里调度了两个事件,不过第一个事件随后被取消了。只运行了第二个事件,所以counter变量只递增一次。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43193719/article/details/94655752
今日推荐