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

yipeiwu_com5年前Python基础

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

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

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()

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

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

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() 

相关文章

python实现数值积分的Simpson方法实例分析

本文实例讲述了python实现数值积分的Simpson方法。分享给大家供大家参考。具体如下: #coding = utf-8 #simpson 法计算积分,数值积分,效果非常理想 f...

Python远程视频监控程序的实例代码

老板由于事务繁忙无法经常亲临教研室,于是让我搞个监控系统,让他在办公室就能看到教研室来了多少人。o(>﹏<)o||| 最初我的想法是直接去网上下个软件,可是找来找去不是有毒就...

Python openpyxl读取单元格字体颜色过程解析

问题 我试图打印some_cell.font.color.rgb并得到各种结果。 对于一些人,我得到了我想要的东西(比如“ FF000000”),但对于其他人,它给了我Value mus...

Python中的元组介绍

Python中的元组介绍

1.元组的创建 元组(tuple):元组本身是不可变数据类型,没有增删改查 元组内可以存储任意数据类型 t = (1,2.3,True,'star') ##例如这里面有数字,波尔...

python使用fileinput模块实现逐行读取文件的方法

本文实例讲述了python使用fileinput模块实现逐行读取文件的方法。分享给大家供大家参考。具体实现方法如下: #-------------------------------...