当前位置:   article > 正文

【python】详解threading模块:timer类的使用(五)_python threading.timer

python threading.timer
Timer(定时器)是Thread的派生类,用于在指定时间后调用一个方法。Timer从Thread派生,没有增加实例方法。

函数:Timer(interval, function, args=[ ], kwargs={ })

  • interval: 指定的时间
  • function: 要执行的方法
  • args/kwargs: 方法的参数
1、timer在t时间后启动
import threading


def func(num):
    print('hello {} timer!'.format(num))

# 如果t时候启动的函数是含有参数的,直接在后面传入参数元组
timer = threading.Timer(5, func,(1,))
time0 = time.time()
timer.start()
print(time.time()-time0)
------------------------------------------------
0.0
hello 1 timer!
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
2、timer可被取消

Timers通过调用它们的start()方法作为线程启动。timer可以通过调用cancel()方法(在它的动作开始之前)停止。timer在执行它的动作之前等待的时间间隔可能与用户指定的时间间隔不完全相同。

  • cancel() :停止timer,并取消timer动作的执行。这只在timer仍然处于等待阶段时才工作。
from threading import Timer

def fun():
    print "hello, world"

if __name__=='__main__':
    t = Timer(5.0, fun)
    t.start() # 开始执行线程,但是不会打印"hello, world"
    t.cancel() # 因为cancel取消了线程的执行,所以fun()函数不会被执行
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/863784
推荐阅读
相关标签
  

闽ICP备14008679号