python 定时器功能的实现方法

Python主要有三种数据类型:字典、列表、元组。其分别由花括号,中括号,小括号表示。
如:
字典:dic={'a':12,'b':34}
列表:list=[1,2,3,4]
元组:tup=(1,2,3,4)
下面是我写的一个可以执行的例子。
import time
import threading
def threadFunc():
    print 'func() passed to Thread. n times already!'
class TimerThread(threading.Thread):
    def __init__(self, fn, args=(), sleep=1, lastDo = True):
        threading.Thread.__init__(self)
        self.fn = fn
        self.args = args
        self.sleep = sleep
        self.lastDo = lastDo
#        self.setDaemon(True)
        self.isPlay = True
        self.fnPlay = False
    def __do(self):
        self.fnPlay = True
        apply(self.fn, self.args)
        self.fnPlay = False
    def run(self):
        while self.isPlay:
            time.sleep(self.sleep)
            self.__do()
    def stop(self):
        self.isPlay = False
        while True:
            if not self.fnPlay:
                break
            time.sleep(0.01)
        if self.lastDo:
            self.__do()
mytimer = TimerThread(threadFunc, '', 2)
mytimer.start()
#mytimer.join()
while True:
    time.sleep(5)
    print 'this is main thread.'
 
 

你可能感兴趣的:(python 定时器功能的实现方法)