Last active
December 20, 2015 22:29
-
-
Save klb3713/6205251 to your computer and use it in GitHub Desktop.
Python 定时器:在定时执行这些操作的时候,我们并不想影响主程序的正常进行,所以我们继承了线程类,有2个标记符,这两个标记符用来保证程序退出时候能够正常退出(执行完毕才退出,而不是直接退出),另外lastDo这个标记符用来申明当定时器收到结束命令的时候是否最后执行一次程序,以保证数据的完整。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment