多次调用thread.timer() [英] Calling thread.timer() more than once
本文介绍了多次调用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
所以我该如何处理这个错误.我想多次启动计时器.
After running this script I get error: RuntimeError: threads can only be started once
so how do I deal with this error. I want to start the timer more than once.
推荐答案
threading.Timer
继承threading.Thread
.线程对象不可重用.您可以为每个调用创建Timer
实例.
threading.Timer
inherits threading.Thread
. Thread object is not reusable. You can create Timer
instance for each call.
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()
这篇关于多次调用thread.timer()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文