I am using Python 2.7. I have a timer that keeps repeating a timer callback action until it has been stopped. It uses a Timer object. The problem is that after it has been stopped, it cannot be restarted. The Timer object code is as follows;
from threading import Timer
class RepeatingTimer(object):
def __init__(self,interval, function, *args, **kwargs):
super(RepeatingTimer, self).__init__()
self.args = args
self.kwargs = kwargs
self.function = function
self.interval = interval
def start(self):
self.callback()
def stop(self):
self.interval = False
def callback(self):
if self.interval:
self.function(*self.args, **self.kwargs)
Timer(self.interval, self.callback, ).start()
To start the timer, the code below is run;
repeat_timer = RepeatingTimer(interval_timer_sec, timer_function, arg1, arg2)
repeat_timer.start()
To stop the timer, the code is;
repeat_timer.stop()
After it is stopped, I tried to restart the timer by calling repeat_timer.start()
but the timer is unable to start. How can the timer be made to restart after it has been stopped?
Thank you.
The reason your timer is not restarting is because you never reset
self.interval
toTrue
before trying to restart the timer. However, if that's the only change you make, you will find your timer is vulnerable to a race condition that will result in more than one timer running concurrently.Here is a corrected version:
Example Run: