第十四章:应用构建模块-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变量只递增一次。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值