您当前的示例运行到的递归限制的问题,因为它的方式调用本身递归地。堆栈大小继续增长并增长,直到达到默认值1000,最有可能。看到这个变形例:
import time
import inspect
import thread
tx1 = time.time()
def loop(event):
print "Stack size: %d" % len(inspect.stack())
tx2 = time.time()
if tx2-tx1 > 0.7:
print "Running code."
return loop(1)
thread.start_new_thread(loop, (1,))
time.sleep(60)
## OUTPUT ##
Stack size: 1
Running code.
Stack size: 2
Running code.
...
Stack size: 999
Running code.
Exception RuntimeError: 'maximum recursion depth exceeded in ...
它可能比较容易使用,可以运行,直到你告诉它停止自定义Thread类。这样堆栈大小不会继续增长。它只是循环并调用你的处理函数。 下面是一个完整的工作例如:
import time
from threading import Thread
class IntervalTimer(Thread):
def __init__(self, secs, func, args=(), kwargs={}):
super(IntervalTimer, self).__init__(target=func, args=args, kwargs=kwargs)
self.__interval = secs
self.__func = func
self.__args = args
self.__kwargs = kwargs
self.__exiting = False
def run(self):
while not self.__exiting:
time.sleep(self.__interval)
self.__func(*self.__args, **self.__kwargs)
def cancel(self):
self.__exiting = True
def test(val):
print val
if __name__ == "__main__":
t = IntervalTimer(2, test, args=("Hi",))
t.start()
time.sleep(10)
t.cancel()
来源
2011-10-07 21:17:43
jdi
这可能会帮助您:http://stackoverflow.com/questions/156330/get-timer-ticks-in-python – GoingTharn
你们是不是要达到一个延迟计时器?在这个例子中,一旦时间超过0.7,它会不断运行你的重复代码,直到你再次触及tx1值,这将需要保护,因为它的共享内存 – jdi
@jdi只是一个计时器,在tot毫秒后重复函数 – Pella86