The best way is to start the timer thread once. Inside your timer thread you'd code the following
class MyThread(Thread):
def __init__(self, event):
Thread.__init__(self)
self.stopped = event
def run(self):
while not self.stopped.wait(0.5):
print("my thread")
# call a function
In the code that started the timer, you can then set the stopped event to stop the timer.
stopFlag = Event()
thread = MyThread(stopFlag)
thread.start()
# this will stop the timer
stopFlag.set()
Answer from Hans Then on Stack OverflowThe best way is to start the timer thread once. Inside your timer thread you'd code the following
class MyThread(Thread):
def __init__(self, event):
Thread.__init__(self)
self.stopped = event
def run(self):
while not self.stopped.wait(0.5):
print("my thread")
# call a function
In the code that started the timer, you can then set the stopped event to stop the timer.
stopFlag = Event()
thread = MyThread(stopFlag)
thread.start()
# this will stop the timer
stopFlag.set()
Improving a little on Hans Then's answer, we can just subclass the Timer function. The following becomes our entire "repeat timer" code, and it can be used as a drop-in replacement for threading.Timer with all the same arguments:
from threading import Timer
class RepeatTimer(Timer):
def run(self):
while not self.finished.wait(self.interval):
self.function(*self.args, **self.kwargs)
Usage example:
def dummyfn(msg="foo"):
print(msg)
timer = RepeatTimer(1, dummyfn)
timer.start()
time.sleep(5)
timer.cancel()
produces the following output:
foo
foo
foo
foo
and
timer = RepeatTimer(1, dummyfn, args=("bar",))
timer.start()
time.sleep(5)
timer.cancel()
produces
bar
bar
bar
bar
Videos
You just need to put the arguments to hello into a separate item in the function call, like this,
t = threading.Timer(10.0, hello, [h])
This is a common approach in Python. Otherwise, when you use Timer(10.0, hello(h)), the result of this function call is passed to Timer, which is None since hello doesn't make an explicit return.
An alternative is to use lambda if you want to use normal function parameters. Basically it tells the program that the argument is a function and not to be called on assignment.
t = threading.Timer(10.0, lambda: hello(h))