用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() 

相关文章

在linux下实现 python 监控usb设备信号

1. linux下消息记录 关于系统的各种消息一般都会记录在/var/log/messages文件中,有些主机在中默认情况下有可能没有启用,具体配置方法可参考下面这篇博客: 系统日志配置...

Python基于最小二乘法实现曲线拟合示例

Python基于最小二乘法实现曲线拟合示例

本文实例讲述了Python基于最小二乘法实现曲线拟合。分享给大家供大家参考,具体如下: 这里不手动实现最小二乘,调用scipy库中实现好的相关优化函数。 考虑如下的含有4个参数的函数式:...

如何用python写一个简单的词法分析器

如何用python写一个简单的词法分析器

编译原理老师要求写一个java的词法分析器,想了想决定用python写一个。 目标 能识别出变量,数字,运算符,界符和关键字,用excel表打印出来。 有了目标,想想要怎么实现词法分析器...

python按行读取文件并找出其中指定字符串

python按行读取文件并找出其中指定字符串 #coding=utf-8 import os, time, sys, re #reload(sys) #sys.setdefaul...

python中datetime模块中strftime/strptime函数的使用

python中datetime模块中strftime/strptime函数的使用

Python 的datetime模块 其实就是date和time 模块的结合,常见的属性方法都比较常用 比如: datetime.day,datetime.month,datet...