Python
threading
Timer
repeat function
scheduled tasks

threading.Timer - repeat function every 'n' seconds

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Threading in Python is a powerful feature that allows for the execution of multiple threads (smaller units of a process) simultaneously. The threading module provides various ways to deal with threads, one of them being the threading.Timer class. This class can be employed to execute a function repeatedly at intervals by wrapping it inside a timer. Here, we'll explore how to achieve this and look into specific use cases and key information regarding this method.

The threading.Timer Class

The threading.Timer class is a subclass of Thread used to create a thread that runs a function after a specified interval has passed. This is particularly useful for delayed or periodic execution of functions in applications that require synchronization or scheduling without blocking the main thread.

Basic Usage

python
1import threading
2
3def display_message():
4    print("This function is called every 5 seconds")
5
6# Create a Timer object
7timer = threading.Timer(5.0, display_message)
8
9# Start the Timer thread
10timer.start()

In this example, display_message is scheduled to run after 5 seconds.

Repeated Execution

To repeatedly execute a function every n seconds, you'll need to restart the timer at the end of the function call. Here's how you can do it:

python
1import threading
2
3def repeat_function(interval):
4    print("This function is called every {} seconds".format(interval))
5    # Restart the timer
6    threading.Timer(interval, repeat_function, [interval]).start()
7
8# Call with desired interval
9repeat_function(5.0)

Explanation

  • Interval: The time in seconds between executions.
  • Function: The task or function you want to be executed.
  • Arguments: Any arguments that the function requires.

Each execution of the function creates a new timer instance that starts going immediately, scheduling the next call of the function.

Advantages

  1. Non-blocking: The main thread continues to run while the timer operates in a separate thread.
  2. Ease of Use: Offers an easy way to manage periodic tasks without an explicit loop.
  3. Flexibility: Simple to use for event-driven or scheduled tasks.

Limitations

  1. Precision: Not suitable for high precision timing. Delays in execution can occur due to thread switching and processing overhead.
  2. Resource Management: Can lead to resource consumption issues if not managed properly, especially with short intervals.

Use Cases

  • Periodic Data Fetching: Regularly fetching data from an API or sensor.
  • UI Updates: Refreshing UI components at regular intervals without freezing.
  • Monitoring: Scheduled monitoring of system resources or file changes.

Comparing Threading.Timer to Other Approaches

Here's a quick comparison with some other methods in Python for periodically executing functions:

MethodNon-blockingPrecisionUse Case
threading.TimerYesLowSuitable for simple periodic tasks with no high precision requirements
sched.schedulerNoHighTasks requiring precise timing and managed events
asyncioYesHighAsynchronous I/O operations and high-level structured tasks
while loopNoVariableSimple repetition when blocking is not an issue

Conclusion

The threading.Timer class offers a straightforward means for implementing periodic function execution in Python. Its non-blocking nature makes it suitable for applications where you wish to keep the main thread responsive. However, for high precision requirements, more sophisticated scheduling tools like sched.scheduler or asyncio might be better suited. Before implementing this approach, consider your task's timing accuracy needs and resource implications.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.