By using
Timer object, you can trigger (or) run a method after a certain amount of time
has passed. Timer is a sub class of Thread class, so you need to call the start
method to start Timer.
How to define a Timer
By using
threading.Timer class, you can define a Timer.
threading.Timer(interval,
function, args=None, kwargs=None)
interval: Interval
represents the time in seconds
function: Method
to be called after amount of time has passed
args: Represent
arguments of method
kwargs:
Represents keyword arguments
Can I cancel the Timer?
Yes, by
using cancel() method, you can stop the timer, and cancel the execution of the
timer’s action. This will only work if the timer is still in its waiting stage.
TimerEx.py
import threading def hello(): print("Hello") def adieu(): print("Good Bye") timer1 = threading.Timer(10.0, hello) timer2 = threading.Timer(20.0, adieu) timer1.start() timer2.start()
$ python3 TimerEx.py Hello Good Bye
No comments:
Post a Comment