发布于 2015-05-08 13:59:49 | 248 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Python3 官方中文指南,程序狗速度看过来!

Python编程语言

Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。


这篇文章主要介绍了用Python编写简单的定时器的方法,主要用到了Python中的threading模块,需要的朋友可以参考下

下面介绍以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() 


最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务