How to create a timer in Python

Timers in Python allow you to schedule and execute code at specific intervals. They are useful for implementing timeouts or performing periodic updates. In Python, you can utilize the time module for basic timing operations or the threading module for more advanced and precise timing requirements.

Timer
Timer

Different types of timers

In Python, a timer is a program used for tracking time. There are two fundamental categories of timers.

  • Stopwatch timers: Timers that start from zero and increment are commonly referred to as stopwatches. These stopwatches are useful for recording and measuring the duration it takes to finish a particular task.

  • Countdown timers: These timers are established with a designated time duration that diminishes until the timer reaches zero. They are commonly used to create time limits, implement timeouts, schedule reminders, or trigger actions at specific points in time.

Implementing timers in Python

Python offers the option to construct timers from scratch using either the threading module or the time module. In the following example, we will explore implementations of both stopwatch timers and countdown timers in Python, showing their functionality.

Countdown timer

You can create a countdown timer using the threading module in Python, which allows a function to be executed after a specified number of seconds. This is a basic example of triggering an action after waiting for a few seconds.

Threading module

import threading
def welcome():
print("Welcome to Educative!")
# Create a timer that executes the welcome() function after 5 seconds
timer = threading.Timer(5.0, welcome)
timer.start()
# The timer will wait for 5 seconds and then print Welcome to Educative!"
  • Lines 3–4: Defines function named welcome() that simply prints "Welcome to Educative!" when called.

  • Line 7: This line creates a timer object named timer using the Timer class from the threading module. It specifies that the welcome() function should be executed after a delay of 5 seconds.

  • Line 8: This line starts the timer. It initiates the countdown of 5 seconds and triggers the function welcome() after 5 seconds.

Time module

import time
def welcome():
print("Welcome to Educative!")
# Delay the execution of the welcome() function by 5 seconds
time.sleep(5.0)
welcome()
  • Line 7: Use the time.sleep(5.0) function to delay the program's execution by 5 seconds which depicts the behavior of a countdown timer.

  • Line 8: Invokes the welcome() function once the countdown timer has completed its delay.

Stopwatch timer

Creating a stopwatch timer can be complex since it needs to run indefinitely and can pause whenever desired.

Constructing a very basic stopwatch timer requires the functionality of start and stop, which we will see in the example given below.

import time
class Stopwatch:
def __init__(self):
self.start_time = None
def start(self):
self.start_time = time.time()
def stop(self):
if self.start_time is None:
raise ValueError("Stopwatch has not been started.")
elapsed_time = time.time() - self.start_time
self.start_time = None
return elapsed_time
# Usage example
stopwatch = Stopwatch()
stopwatch.start()
# Simulate some time-consuming task
time.sleep(2.5)
elapsed_time = stopwatch.stop()
print(f"Elapsed time: {elapsed_time:.2f} seconds")
  • Lines 3–15: We define a Stopwatch class that has two methods: start() and stop() .

    • Lines 7–8: The start() method records the start time using time.time() .

    • Lines 1015: The stop() method calculates the elapsed time by subtracting the start time from the current time.

  • Lines 18–19: We create an instance of the Stopwatch class and call the start() method to start the stopwatch timer.

  • Line 22: We simulate a time-consuming task by using time.sleep(2.5) to pause the program for 2.5 seconds.

  • Line 24: After the task completes, we call the stop() method to stop the stopwatch timer and print the elapsed time. Elapsed time refers to the duration or amount of time that has passed between a specific start point and the current moment.

Conclusion

Timers in Python provide a powerful mechanism for scheduling and executing code based on time intervals. By using the time or threading module, you can easily incorporate timers into your Python programs and enhance their functionality.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved