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

yipeiwu_com6年前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使用range函数计算一组数和的方法

本文实例讲述了python使用range函数计算一组数和的方法。分享给大家供大家参考。具体如下: sum = 0 numbers = range(1,10) for i in num...

使用apidoc管理RESTful风格Flask项目接口文档方法

使用apidoc管理RESTful风格Flask项目接口文档方法

使用apidoc管理RESTful风格Flask项目接口文档方法 apidoc项目地址 flask扩展包地址 文档示例地址 1.安装nodejs sudo apt-get insta...

Python 单例设计模式用法实例分析

本文实例讲述了Python 单例设计模式用法。分享给大家供大家参考,具体如下: demo.py(单例): class MusicPlayer(object): # 类属性 记录对...

python3的print()函数的用法图文讲解

python3的print()函数的用法图文讲解

Python 3 print 函数 基础代码 1、print语法格式 print()函数具有丰富的功能,详细语法格式如下: print(value, ..., sep=' ', end=...

python模仿网页版微信发送消息功能

python模仿网页版微信发送消息功能

这个微信版网页版虽然繁琐,但是不是很难,全程不带加密的。有兴趣的可以试着玩一玩,如果有兴趣的话,可以完善一下,做一些比较有意思的东西。 开发环境:Windows10 开发语言:Pytho...