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.

import time
import threading

def main():
    # Timers represent a single event in the future. You
    # tell the timer how long you want to wait, and it
    # will execute a function after that time. This timer
    # will wait 2 seconds.
    timer1 = threading.Timer(2.0, lambda: print("Timer 1 fired"))
    timer1.start()

    # The timer1.join() blocks until the timer fires and the
    # function completes.
    timer1.join()

    # If you just wanted to wait, you could have used
    # time.sleep(). One reason a timer may be useful is
    # that you can cancel the timer before it fires.
    # Here's an example of that.
    timer2 = threading.Timer(1.0, lambda: print("Timer 2 fired"))
    timer2.start()
    
    # Cancel the timer
    timer2.cancel()
    print("Timer 2 stopped")

    # Give the timer2 enough time to fire, if it ever
    # was going to, to show it is in fact stopped.
    time.sleep(2)

if __name__ == "__main__":
    main()

To run the program, save it as timers.py and use python:

$ python timers.py
Timer 1 fired
Timer 2 stopped

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:

  1. 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.

  2. We start the timer with the start() method, which begins the countdown.

  3. 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.

  4. For the second timer, we demonstrate how to cancel it using the cancel() method.

  5. 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.