1. 程式人生 > >python threading模組、Timer類講解

python threading模組、Timer類講解

16.2.7. Timer Objects

# The timer class was contributed by Itamar Shtull-Trauring

def Timer(*args, **kwargs):
    """Factory function to create a Timer object.

    Timers call a function after a specified number of seconds:

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

    """
    return _Timer(*args, **kwargs)

翻譯:Timer工廠函式,返回一個定時器物件,定時器物件負責呼叫函式,在指定的時間之後。

真正的定時器類:_Timer

class _Timer(Thread): #繼承Thread類
    """Call a function after a specified number of seconds:

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

    """

    def __init__(self, interval, function, args=[], kwargs={}): #重寫建構函式
        Thread.__init__(self) #呼叫父類建構函式
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = Event() #內部事件類,用來定時作用

    def cancel(self): #自定義cancel方法,取消定時器執行
        """Stop the timer if it hasn't finished yet"""
        self.finished.set()

    def run(self): #重寫run方法
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()

演示:

import threading

def hello():
    print 'hello world!!!'



ti=threading.Timer(interval=3,function=hello)

ti.start()

執行結果:

C:\Python27\python.exe E:/pythonproj/基礎練習/t8.py
hello world!!!

Process finished with exit code 0