第十章:使用进程、线程和协程提供并发性-threading:进程中管理并发操作-定时器线程

10.3.6 定时器线程
有时出于某种原因需要派生Thread,Timer就是这样一个例子,Timer也包含在Threading中。Timer在一个延迟之后开始工作,而且可以在这个延迟期间内的任意时刻被取消。

import threading
import time
import logging

def delayed():
    logging.debug('worker running')

logging.basicConfig(
    level=logging.DEBUG,
    format='(%(threadName)-10s) %(message)s',
    )

t1 = threading.Timer(0.3,delayed)
t1.setName('t1')
t2 = threading.Timer(0.3,delayed)
t2.setName('t2')

logging.debug('starting timers')
t1.start()
t2.start()

logging.debug('waiting before canceling %s',t2.getName())
time.sleep(0.2)
logging.debug('canceling %s',t2.getName())
t2.cancel()
logging.debug('done')

这个例子中,第二个定时器永远不会运行,看起来第一个定时器在主程序的其余部分完成之后还会运行,由于这不是一个守护线程,所以在主线程完成时其会隐式退出。
运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43193719/article/details/89597748