Python 定时器
时间:2011-05-31 来源:simayixin
在编写服务进程的时候,往往需要定时落地一些数据,这就需要定时来执行一些操作,然后python中并没有合适的定时器(我没有找到),就自己diy吧。
import threading,time
class Timer(threading.Thread):
def __init__(self,fn,args=(),sleep=0,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):
#stop the loop
self.isPlay = False
while True:
if not self.fnPlay : break
time.sleep(0.01)
#if lastDo,do it again
if self.lastDo : self.__do()
在定时执行这些操作的时候,我们并不想影响主程序的正常进行,所以我们继承了线程类,有2个标记符,这两个标记符用来保证程序退出时候能够正常退出(执行完毕才退出,而不是直接退出),另外lastDo这个标记符用来申明当定时器收到结束命令的时候是否最后执行一次程序,以保证数据的完整。
相关阅读 更多 +










