🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The threading.Timer class in Python's threading module provides a way to execute a function after a specified delay. This is useful for scheduling tasks to run after a certain period of time has elapsed.
Table of Contents
- Introduction
threading.TimerClass Syntax- Examples
- Basic Usage
- Using Timer with Arguments
- Stopping a Timer
- Real-World Use Case
- Conclusion
Introduction
The threading.Timer class is used to create a timer that runs a function after a specified amount of time. This can be useful for tasks that need to be delayed, scheduled, or repeated after a certain interval.
threading.Timer Class Syntax
Here is how you create and use a timer with the threading.Timer class:
import threading
timer = threading.Timer(interval, function, args=None, kwargs=None)
Parameters:
interval: The number of seconds to wait before executing the function.function: The function to be executed.args: Optional. A tuple of positional arguments to pass to the function.kwargs: Optional. A dictionary of keyword arguments to pass to the function.
Methods:
start(): Start the timer.cancel(): Stop the timer if it hasn’t finished yet.
Examples
Basic Usage
Create and start a timer to run a function after a delay.
Example
import threading
import time
def hello():
print("Hello, world!")
timer = threading.Timer(5, hello)
timer.start()
print("Timer started, waiting for 5 seconds...")
Output:
Timer started, waiting for 5 seconds...
Hello, world!
Using Timer with Arguments
Create a timer that runs a function with arguments.
Example
import threading
import time
def greet(name):
print(f"Hello, {name}!")
timer = threading.Timer(3, greet, args=("Alice",))
timer.start()
print("Timer started, waiting for 3 seconds...")
Output:
Timer started, waiting for 3 seconds...
Hello, Alice!
Stopping a Timer
Create and cancel a timer before it executes.
Example
import threading
import time
def goodbye():
print("Goodbye, world!")
timer = threading.Timer(5, goodbye)
timer.start()
print("Timer started, but will be canceled in 2 seconds...")
time.sleep(2)
timer.cancel()
print("Timer canceled.")
Output:
Timer started, but will be canceled in 2 seconds...
Timer canceled.
Real-World Use Case
Repeating Task with Timer
Use a timer to schedule a repeating task.
Example
import threading
import time
def print_message():
print("This message is printed every 2 seconds")
global timer
timer = threading.Timer(2, print_message)
timer.start()
# Start the repeating task
timer = threading.Timer(2, print_message)
timer.start()
# Run the task for 10 seconds and then stop
time.sleep(10)
timer.cancel()
print("Repeating task stopped.")
Output:
This message is printed every 2 seconds
This message is printed every 2 seconds
This message is printed every 2 seconds
This message is printed every 2 seconds
This message is printed every 2 seconds
Repeating task stopped.
Conclusion
The threading.Timer class is used for scheduling tasks to run after a certain delay. It can be used to create simple delays, schedule tasks with arguments, and even create repeating tasks. Proper usage can enhance the timing and scheduling capabilities of your Python programs.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment