Tickers in Python

Timers are for when you want to do something once in the future - tickers are for when you want to do something repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.

import time
import threading

def ticker():
    while not done_event.is_set():
        if not ticker_event.wait(0.5):  # Wait for 500ms
            print(f"Tick at {time.ctime()}")

def main():
    global done_event, ticker_event
    done_event = threading.Event()
    ticker_event = threading.Event()

    ticker_thread = threading.Thread(target=ticker)
    ticker_thread.start()

    # Let the ticker run for 1600ms
    time.sleep(1.6)

    # Stop the ticker
    done_event.set()
    ticker_thread.join()
    print("Ticker stopped")

if __name__ == "__main__":
    main()

In this Python version, we use the threading module to create a similar mechanism to Go’s tickers. We create a separate thread that runs the ticker function.

The ticker function uses a loop that continues until a done_event is set. It uses ticker_event.wait(0.5) to create a delay of 500ms between each tick. If the wait times out (which it will every 500ms), it prints the current time.

In the main function, we create the necessary Event objects, start the ticker thread, let it run for 1600ms, and then stop it by setting the done_event.

When we run this program, the ticker should tick 3 times before we stop it.

$ python tickers.py
Tick at Sun Sep 23 11:29:56 2023
Tick at Sun Sep 23 11:29:57 2023
Tick at Sun Sep 23 11:29:57 2023
Ticker stopped

This Python implementation provides similar functionality to the original example, using Python’s threading capabilities to simulate the behavior of Go’s tickers.