如何让这个计时器永远运行?
from threading import Timer
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start()
这段代码只会让计时器运行一次。
我该怎么做才能让计时器一直运行呢?
谢谢,
更新
这个是对的:
import time,sys
def hello():
while True:
print "Hello, Word!"
sys.stdout.flush()
time.sleep(2.0)
hello()
还有这个:
from threading import Timer
def hello():
print "hello, world"
sys.stdout.flush()
t = Timer(2.0, hello)
t.start()
t = Timer(2.0, hello)
t.start()
5 个回答
2
你可以通过创建一个新的类来实现一个重复的计时器,这个新类是从 threading.Timer
类继承而来的。然后,你需要重写 run
方法,让它使用一个循环。
from threading import Timer
class RepeatingTimer(Timer):
def run(self):
"""Start the timer (overrides Thread.run)."""
while True:
# Wait for the set flag or timeout.
self.finished.wait(timeout=self.interval)
if not self.finished.is_set():
self.function(*self.args, **self.kwargs)
else:
# Do not need to set the finished event flag since this loop
# will only end if the flag is set.
break
9
只需要在这个函数里重新启动(或者重新创建)计时器就可以了:
#!/usr/bin/python
from threading import Timer
def hello():
print "hello, world"
t = Timer(2.0, hello)
t.start()
t = Timer(2.0, hello)
t.start()
9
threading.Timer
是用来执行一个函数的,它只会执行一次。如果你想让这个函数“永远运行”,也是可以的,比如:
import time
def hello():
while True:
print "Hello, Word!"
time.sleep(30.0)
如果你使用多个 Timer
实例,会消耗很多资源,但其实并没有什么实际的好处。如果你想在每30秒重复执行一个函数,但又不想对这个函数做太多改动,一个简单的方法就是:
import time
def makerepeater(delay, fun, *a, **k):
def wrapper(*a, **k):
while True:
fun(*a, **k)
time.sleep(delay)
return wrapper
然后你可以安排 makerepeater(30, hello)
来代替直接调用 hello
。
如果你需要更复杂的操作,我推荐使用标准库中的 sched 模块。