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.
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
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:
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
- Non-blocking: The main thread continues to run while the timer operates in a separate thread.
- Ease of Use: Offers an easy way to manage periodic tasks without an explicit loop.
- Flexibility: Simple to use for event-driven or scheduled tasks.
Limitations
- Precision: Not suitable for high precision timing. Delays in execution can occur due to thread switching and processing overhead.
- 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:
| Method | Non-blocking | Precision | Use Case |
threading.Timer | Yes | Low | Suitable for simple periodic tasks with no high precision requirements |
sched.scheduler | No | High | Tasks requiring precise timing and managed events |
asyncio | Yes | High | Asynchronous I/O operations and high-level structured tasks |
while loop | No | Variable | Simple 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
- ThreadPoolExecutor Block When its Queue Is Full?
- ThreadPoolExecutor with corePoolSize 0 should not execute tasks until task queue is full
- ThreadPool.QueueUserWorkItem vs Task.Factory.StartNew
- Threads and Reactive Programming in Ballerina
- Threads is not executing in parallel python with ThreadPoolExecutor
- Threads vs Asynchronous Networking Twisted Python
- Threads configuration based on no. of CPU-cores
- Threads vs. Async
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.