用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中 传递值 和 传递引用 的区别解析

Python中 传递值 和 传递引用 的区别解析

对于不可变类型传递值(不会影响原数据)   不可变类型 对于可变类型传递引用(会影响原数据)   不可变类型传递引用 python3不可变类型 Number(数...

Python CVXOPT模块安装及使用解析

Python CVXOPT模块安装及使用解析

Python中支持Convex Optimization(凸规划)的模块为CVXOPT,其安装方式为: 卸载原Pyhon中的Numpy 安装CVXOPT的whl文件,链接为:https...

Python实现带参数的用户验证功能装饰器示例

本文实例讲述了Python实现带参数的用户验证功能装饰器。分享给大家供大家参考,具体如下: user_list = [ {'name': 'sb1', 'passwd': '12...

Python二叉树的定义及常用遍历算法分析

本文实例讲述了Python二叉树的定义及常用遍历算法。分享给大家供大家参考,具体如下: 说起二叉树的遍历,大学里讲的是递归算法,大多数人首先想到也是递归算法。但作为一个有理想有追求的程序...

python实现RSA加密(解密)算法

python实现RSA加密(解密)算法

RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准。 今天只有短的RSA钥匙才可能被强力方式解破。到2008年为止,世界上...