一个简单的python定时器实现,python定时器,下面介绍以threadi
一个简单的python定时器实现,python定时器,下面介绍以threadi
下面介绍以threading模块来实现定时器的方法。使用前先做一个简单试验:
import threading def sayhello(): print "hello world" global t #Notice: use global variable! t = threading.Timer(5.0, sayhello) t.start() t = threading.Timer(5.0, sayhello) t.start()
运行结果如下
>python hello.py hello world hello world hello world
下面是定时器类的实现:
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()
相关内容
- 增强版的cp,增强版cp,完全兼容系统cp特性支持
- 生成四位不重复数字(0-9)的所有组合,四位0-9,Python语言
- Python ConfigParser模块,pythonconfigparser,在程序中使用配置
- python中os模块的常用方法,pythonos模块,import osos.
- python排序|key函数|自定义排序,pythonkey,python本身提供了
- 一个抓取京东手机列表url的小程序,抓取京url小程序
- 怎么使用python在微信中实现远程控制电脑,python实现远
- 从姐脱吧下载妹子图片,,我看好多人写着玩,下载下
- locals() 的另类用法,locals另类用法,d = {'a':1,
- HTML颜色和RGB颜色互转,html颜色rgb,Python语言: HT
评论关闭