python 定时器
来源:互联网 发布:java调用存储过程 编辑:程序博客网 时间:2024/05/01 09:47
1. Timer
def hello(name): print 'hello world, i am %s, Current time: %s' % (name, time.time()) hello = partial(hello, 'guo') t = Timer(3, hello)t.start()
但是只执行一次,想办法做成一个真正的定时器:
def hello(name): global t t = Timer(3, hello) t.start() print 'hello world, i am %s, Current time: %s' % (name, time.time()) hello = partial(hello, 'guo') t = Timer(3, hello)t.start()
2. sched
def hello(name): print 'hello world, i am %s, Current Time:%s' % (name, time.time())s = sched.scheduler(time.time, time.sleep)s.enter(3, 2, hello, ('guo',))s.run()
和Timer是一样的效果,再修改:
def hello(name): print 'hello world, i am %s, Current Time:%s' % (name, time.time()) run(name) def run(name): s = sched.scheduler(time.time, time.sleep) s.enter(3, 2, hello, (name,)) s.run() s = sched.scheduler(time.time, time.sleep)s.enter(3, 2, hello, ('guo',))s.run()
3. threading
repeatTimer.py
from threading import Event, Thread class RepeatTimer(Thread): def __init__(self, interval, function, iterations=0, args=[], kwargs={}): Thread.__init__(self) self.interval = interval self.function = function self.iterations = iterations self.args = args self.kwargs = kwargs self.finished = Event() def run(self): count = 0 while not self.finished.is_set() and (self.iterations <= 0 or count < self.iterations): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) count += 1 def cancel(self): self.finished.set()
def hello(name): print 'hello world, i am %s, Current Time:%s' % (name, time.time()) hello = partial(hello, 'guo')#r = RepeatTimer(5.0, hello, 3)r = RepeatTimer(5.0, hello)r.start()
4. sleep
当然最简单的办法还是循环+sleep:
def hello(name): print 'hello world, i am %s, Current Time:%s' % (name, time.time()) if __name__=='__main__': while True: hello('guo') sleep(3)不过这样看起来太不专业了。。
5. 如果是大型项目中需要用到定时或周期做某个事情,前面所说的就有点不太敬业了
推荐:celeryd+rabbitmq,很强大
--------------------------
感谢:http://g-off.net/software/a-python-repeatable-threadingtimer-class
http://www.coder4.com/archives/1589
- Python定时器
- python 定时器
- python定时器
- Python定时器
- Python 定时器
- python 定时器
- python 定时器
- python定时器
- python定时器
- Python 定时器
- python 定时器
- Python定时器
- Python定时器
- Python定时器
- python 应用crontab 定时器
- Python 定时器 timer
- Python 定时器 timer
- python编程(定时器)
- 更改当前数据库中 SQL Server 用户与 Microsoft® SQL Server™ 登录之间的关系
- 404 图片
- 联通和电信的流媒体播放
- 再谈iframe自适应高度(http://www.cnblogs.com/MaxIE/archive/2008/08/13/1266597.html)
- JsonSerializable接口
- python 定时器
- 使用ssh或scp无需输入密码方法
- 求助-关于自动还原---
- 黑马程序员--编程基础学习笔记二
- 如何android多Activity间共享数据
- WebRtc代码分布
- java堆栈
- 二层交换机下带用户ARP攻击处理
- PHP APC安装与使用