用Python编写简单的定时器的方法
2015-05-02 00:00
666 查看
下面介绍以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编写简单的定时器的方法
- Windows下用python编写简单GUI程序的方法
- python 之简单畅聊一下静态方法和动态方法
- 使用python语言结合beautifulsoup编写简单的网络爬虫
- python调用c语言函数的一种简单实现方法
- vc6编写python扩展的方法分享
- Python实现简单的用户交互方法详解
- D7中编写NT服务操作数据库的简单方法
- python实现超简单端口转发的方法
- VS平台简单的使用C++调用Python3.5的方法
- Python使用shelve模块实现简单数据存储的方法
- 利用python 编写 简单 虚拟机管理
- 使用Python编写简单网络爬虫抓取视频下载资源
- python使用wxpython开发简单记事本的方法
- 使用Python的Scrapy框架编写web爬虫的简单示例
- Python简单实现TCP包发送十六进制数据的方法
- python脚本实现数据导出excel格式的简单方法(推荐)
- 应用python编写简单新浪微博应用(二)
- python3.X安装matplotlib简单方法
- python处理图片之PIL模块简单使用方法