python 定时器 threading.timer到底怎么用?


自己摸索才能真正理解python的threading.Timer()定时器的用法。

首先让我们看下Timer的源码,怎么定义这个定时时间的:

需要操作的任务在达到设置的定时时间还没有结束,调用Timer()中:调用的函数/方法。

class Timer(Thread):
    """Call a function after a specified number of seconds:

            t = Timer(30.0, f, args=None, kwargs=None)
            t.start()
            t.cancel() # stop the timer's action if it's still waiting """

    def __init__(self, interval, function, args=None, kwargs=None):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args if args is not None else []
        self.kwargs = kwargs if kwargs is not None else {}
        self.finished = Event()

    def cancel(self):
        """Stop the timer if it hasn't finished yet."""
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()

 

举个例子:

import time
from threading import Timer


def fun():
    print("hello, world")


if __name__=='__main__':
    t = Timer(5, fun) # 超过5秒,执行fun函数
    t.start()
    sum = 0
    for i in range(6): 
        sum = i+1
        time.sleep(1)  # 等待了6次超过Timer中的5秒
    t.cancel()  # 结束后将timer取消掉

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM