用Python编写简单的定时器的方法

时间:2022-08-29 09:12:47

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

首先介绍一个最简单实现:

?
1
2
3
4
5
6
7
8
9
10
import threading
 
def say_sth(str):
  print str
  t = threading.Timer(2.0, say_sth,[str])
  t.start()
 
if __name__ == '__main__':
  timer = threading.Timer(2.0,say_sth,['i am here too.'])
  timer.start()

不清楚在某些特殊应用场景下有什么缺陷否。

下面是所要介绍的定时器类的实现:

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