Reputation: 113
What's the difference between threading.Timer
and threading.Thread
?
When I use the Timer function, it starts target command in separate thread with delay.
When I use the Thread function, it starts target command with args in separate thread.
It's the same, I think, isn't it?
Upvotes: 1
Views: 2557
Reputation: 295363
It's worth looking at the implementation.
# _Timer is thinly wrapped by Timer; excluding that wrapper for terseness
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()
Thus, yes, a Timer is just an instance of Thread that invokes your function after a given delay, using the Event mechanism for efficient scheduling and providing a cancel()
that reliably prevents the function from being called at all if the delay has not yet expired.
As we see above, Thread
is the implementation that does the heavy lifting, and Timer
is a helper that adds extra functionality (a delay at the front); Timer(0, func)
wouldn't work if Thread
didn't exist.
A Thread
being an object gives more flexibility than being only able to override the function to be called, without having that function having access to instance variables -- look at Timer
itself, and how it uses that capability to add and respect cancel()
. You can't do that on top of Timer
without subclassing _Timer
, which (as the name implies) is an implementation detail not promised to be stable in future releases.
Thus, Timer()
has more moving parts and is less flexible than Thread()
-- both of those being innate disadvantages in software engineering -- but is handy for a specific moderately-common use case. Why would one not provide both?
Upvotes: 4
Reputation: 16305
You already explained the difference. Thread
is a thread, Timer
is a thread whose execution is deferred for at least a specified time.
https://docs.python.org/2/library/threading.html#timer-objects
Upvotes: 1