多次调用thread.timer()
问题内容:
编码:
from threading import Timer
import time
def hello():
print "hello"
a=Timer(3,hello,())
a.start()
time.sleep(4)
a.start()
运行此脚本后,我收到错误消息:RuntimeError: threads can only be started once
那么如何处理此错误。我想多次启动计时器。
问题答案:
threading.Timer
继承threading.Thread
。线程对象不可重用。您可以Timer
为每个调用创建实例。
from threading import Timer
import time
class RepeatableTimer(object):
def __init__(self, interval, function, args=[], kwargs={}):
self._interval = interval
self._function = function
self._args = args
self._kwargs = kwargs
def start(self):
t = Timer(self._interval, self._function, *self._args, **self._kwargs)
t.start()
def hello():
print "hello"
a=RepeatableTimer(3,hello,())
a.start()
time.sleep(4)
a.start()