Timers in Python
Our first example demonstrates the use of timers in Python. We often want to execute code at some point in the future, or repeatedly at some interval. Python’s time
module and the threading
module make both of these tasks easy. We’ll look first at timers.
To run the program, save it as timers.py
and use python
:
The first timer will fire ~2s after we start the program, but the second should be stopped before it has a chance to fire.
In this Python version:
We use the
threading.Timer
class to create timers. This class takes two arguments: the number of seconds to wait, and the function to call when the timer fires.We start the timer with the
start()
method, which begins the countdown.For the first timer, we use
join()
to wait for it to complete. This is equivalent to blocking on a channel in the original example.For the second timer, we demonstrate how to cancel it using the
cancel()
method.We use
time.sleep()
at the end to give the second timer time to fire (if it was going to), demonstrating that it has indeed been cancelled.
This example shows how to use timers for scheduling tasks in the future and how to cancel them if needed. The threading.Timer
class provides a simple way to run a function after a specified interval, which can be useful for delayed execution or timeout mechanisms in your Python programs.