Calling thread.timer() more than once

后端 未结 2 1782
半阙折子戏
半阙折子戏 2021-01-14 20:49

The code:

from threading import Timer
import time

def hello():
    print \"hello\"

a=Timer(3,hello,())
a.start()
time.sleep(4)
a.start()

2条回答
  •  [愿得一人]
    2021-01-14 21:39

    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()
    

提交回复
热议问题