python 定时器

来源:互联网 发布:新开的淘宝店怎么刷单 编辑:程序博客网 时间:2024/05/22 03:45

博客原址:http://blog.csdn.net/pandarawen/article/details/8496345

下面介绍以threading模块来实现定时器的方法。

使用前先做一个简单试验:

[python] view plaincopyprint?
  1. import threading  
  2. def sayhello():  
  3.         print "hello world"  
  4.         global t        #Notice: use global variable!  
  5.         t = threading.Timer(5.0, sayhello)  
  6.         t.start()  
  7.   
  8. t = threading.Timer(5.0, sayhello)  
  9. t.start()  

运行结果如下

[python] view plaincopyprint?
  1. >python hello.py  
  2. hello world  
  3. hello world  
  4. hello world  

下面是定时器类的实现:

[python] view plaincopyprint?
  1. class Timer(threading.Thread):  
  2.         """ 
  3.         very simple but useless timer. 
  4.         """  
  5.         def __init__(self, seconds):  
  6.                 self.runTime = seconds  
  7.                 threading.Thread.__init__(self)  
  8.         def run(self):  
  9.                 time.sleep(self.runTime)  
  10.                 print "Buzzzz!! Time's up!"  
  11.   
  12. class CountDownTimer(Timer):  
  13.         """ 
  14.         a timer that can counts down the seconds. 
  15.         """  
  16.         def run(self):  
  17.                 counter = self.runTime  
  18.                 for sec in range(self.runTime):  
  19.                         print counter  
  20.                         time.sleep(1.0)  
  21.                         counter -= 1  
  22.                 print "Done"  
  23.   
  24. class CountDownExec(CountDownTimer):  
  25.         """ 
  26.         a timer that execute an action at the end of the timer run. 
  27.         """  
  28.         def __init__(self, seconds, action, args=[]):  
  29.                 self.args = args  
  30.                 self.action = action  
  31.                 CountDownTimer.__init__(self, seconds)  
  32.         def run(self):  
  33.                 CountDownTimer.run(self)  
  34.                 self.action(self.args)  
  35.   
  36. def myAction(args=[]):  
  37.         print "Performing my action with args:"  
  38.         print args  
  39. if __name__ == "__main__":  
  40.         t = CountDownExec(3, myAction, ["hello""world"])  
  41.         t.start()  
0 0