用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的lib目录里有一个:this.py,它其实是隐藏着一首诗,源码如下:复制代码 代码如下:s = """Gur Mra bs Clguba, ol Gvz Crgref...

Django跨域请求CSRF的方法示例

web跨域请求 1.为什么要有跨域限制 举个例子: 1.用户登录了自己的银行页面 http://mybank.com,http://mybank.com向用户的cookie中添加用户...

Python 字符串定义

例如:'string'、"string"、"""string"""或者是'''string'''。在使用上,单引号和双引号没有什么区别。三引号的主要功能是在字符串中可以包含换行。也就是说...

R vs. Python 数据分析中谁与争锋?

R vs. Python 数据分析中谁与争锋?

当我们想要选择一种编程语言进行数据分析时,相信大多数人都会想到R和Python——但是从这两个非常强大、灵活的数据分析语言中二选一是非常困难的。 我承认我还没能从这两个数据科学家喜爱的语...

wxpython 最小化到托盘与欢迎图片的实现方法

一直在学习系统托盘的实现,于是自己写了一个简单的系统托盘实例,右键包括演示、最大化、最小化、退出和关于。在python2.6下测试通过。 注意,本节分享的python实例代码,这里是托盘...