用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 送你一顶圣诞帽 @微信官方

还有多少耿直boy和我一样在等待微信官方送上一顶圣诞帽? 最后知道真相的我眼泪掉下来…… (还蒙在鼓里的同学请在微信最上方的搜索栏自行搜索『圣诞帽』) 好吧,你不给,咱自己来,不就...

python 利用栈和队列模拟递归的过程

一、递归 递归调用:一个函数,调用的自身,称为递归调用 递归函数:一个可以调用自身的函数称为递归函数   凡是循环能干的事,递归都能干 方法: 1、写出临界条件 2、找这一次和上一次的关...

Python装饰器原理与简单用法实例分析

本文实例讲述了Python装饰器原理与简单用法。分享给大家供大家参考,具体如下: 今天整理装饰器,内嵌的装饰器、让装饰器带参数等多种形式,非常复杂,让人头疼不已。但是突然间发现了装饰器的...

详解python编译器和解释器的区别

高级语言不能直接被机器所理解执行,所以都需要一个翻译的阶段,解释型语言用到的是解释器,编译型语言用到的是编译器。 编译型语言通常的执行过程是:源代码——预处理器——编译器——目标代码——...

分分钟入门python语言

Python 是 90 年代初由 Guido Van Rossum 创立的。它是当前最流行的程序语言之一。它那纯净的语法令我一见倾心,它简直就是可以运行的伪码。 请注意:本文以 Pyth...