For threading.Timer Object, is there any way to update the timer time after calling start method ?
for example
timer = threading.Timer(5, function)
timer.start()
#after calling start method, i want to extend the timer time before expired.
as i looked through the document of threading.Timer, there isn't way.
so do i have to call cancel method then call again start method?
The Timer object is really quite simple:
def Timer(*args, **kwargs):
return _Timer(*args, **kwargs)
class _Timer(Thread):
"""Call a function after a specified number of seconds:
t = Timer(30.0, f, args=[], kwargs={})
t.start()
t.cancel() # stop the timer's action if it's still waiting
"""
def __init__(self, interval, function, args=[], kwargs={}):
Thread.__init__(self)
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = Event()
def cancel(self):
"""Stop the timer if it hasn't finished yet"""
self.finished.set()
def run(self):
self.finished.wait(self.interval)
if not self.finished.is_set():
self.function(*self.args, **self.kwargs)
self.finished.set()
It's just waiting calling wait with a timeout on a threading.Event object, then either runs the provided method or exits if cancel was called. You could implement your own version of Timer that supports extending the wait, but the default one definitely doesn't support it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With