如何使此计时器永远运行? [英] How can I make this timer run forever?
本文介绍了如何使此计时器永远运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
from threading import Timer
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start()
此代码仅触发一次计时器.
This code only fires the timer once.
如何使计时器永远运行?
How can I make the timer run forever?
谢谢
已更新
这是正确的:
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()
推荐答案
threading.Timer
一次执行函数 .如果您愿意,该功能可以永远运行",例如:
A threading.Timer
executes a function once. That function can "run forever" if you wish, for example:
import time
def hello():
while True:
print "Hello, Word!"
time.sleep(30.0)
使用多个Timer
实例将消耗大量资源,而没有真正的附加值.如果您希望每30秒重复一次此功能,那么一种简单的方法是:
Using multiple Timer
instances would consume substantial resources with no real added value. If you want to be non-invasive to the function you're repeating every 30 seconds, a simple way would be:
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 .
For more sophisticated operations, I recommend standard library module sched.
这篇关于如何使此计时器永远运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文