多次调用 thread.timer()

Nil*_*Nil 4 python multithreading

编码:

from threading import Timer
import time

def hello():
    print "hello"

a=Timer(3,hello,())
a.start()
time.sleep(4)
a.start()
Run Code Online (Sandbox Code Playgroud)

运行此脚本后,出现错误:RuntimeError: threads can only be started once 那么我该如何处理此错误。我想不止一次启动计时器。

小智 5

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()
Run Code Online (Sandbox Code Playgroud)