python通过线程实现定时器timer的方法
本文实例讲述了python通过线程实现定时器timer的方法。分享给大家供大家参考。具体分析如下:
这个python类实现了一个定时器效果,调用非常简单,可以让系统定时执行指定的函数
下面介绍以threading模块来实现定时器的方法。
使用前先做一个简单试验:
importthreading defsayhello(): print"helloworld" globalt#Notice:useglobalvariable! t=threading.Timer(5.0,sayhello) t.start() t=threading.Timer(5.0,sayhello) t.start()
运行结果如下:
>pythonhello.py helloworld helloworld helloworld
下面是定时器类的实现:
classTimer(threading.Thread): """ verysimplebutuselesstimer. """ def__init__(self,seconds): self.runTime=seconds threading.Thread.__init__(self) defrun(self): time.sleep(self.runTime) print"Buzzzz!!Time'sup!" classCountDownTimer(Timer): """ atimerthatcancountsdowntheseconds. """ defrun(self): counter=self.runTime forsecinrange(self.runTime): printcounter time.sleep(1.0) counter-=1 print"Done" classCountDownExec(CountDownTimer): """ atimerthatexecuteanactionattheendofthetimerrun. """ def__init__(self,seconds,action,args=[]): self.args=args self.action=action CountDownTimer.__init__(self,seconds) defrun(self): CountDownTimer.run(self) self.action(self.args) defmyAction(args=[]): print"Performingmyactionwithargs:" printargs if__name__=="__main__": t=CountDownExec(3,myAction,["hello","world"]) t.start()
以上代码在Python2.5.4中运行通过
希望本文所述对大家的Python程序设计有所帮助。
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短