Last Updated on September 12, 2022
You can use a timer thread object in Python via the threading.Timer class.
In this tutorial you will discover how to use a thread timer object in Python.
Let’s get started.
Need for a Timer Thread
A thread is a thread of execution in a computer program.
Every Python program has at least one thread of execution called the main thread. Both processes and threads are created and managed by the underlying operating system.
Sometimes we may need to create additional threads in our program in order to execute code concurrently.
Python provides the ability to create and manage new threads via the threading module and the threading.Thread class.
You can learn more about Python threads in the guude:
Sometimes in concurrent programming we may want a thread to start executing our code after a time limit has expired.
This can be achieved using a timer thread.
How can we use a timer thread in Python?
Run loops using all CPUs, download your FREE book to learn how.
How to Use a Timer Thread
Python provides a timer thread in the threading.Timer class.
The threading.Timer is an extension of the threading.Thread class, meaning that we can use it just like a normal thread instance.
It provides a useful way to execute a function after an interval of time.
First, we can create an instance of the timer and configure it. This includes the time to wait before executing in seconds, the function to execute once triggered, and any arguments to the target function.
For example:
1 2 3 |
... # configure a timer thread timer = Timer(10, task, args=(arg1, arg2)) |
The target task function will not execute until the time has elapsed.
Once created, the thread must be started by calling the start() function which will begin the timer.
1 2 3 |
... # start the timer thread timer.start() |
If we decide to cancel the timer before the target function has executed, this can be achieved by calling the cancel() function.
For example:
1 2 3 |
... # cancel the timer thread timer.cancel() |
Once the time has elapsed and the target function has executed, the timer thread cannot be reused.
Now that we know how to use a threading.Timer thread, let’s look at some worked examples.
Example of Using a Timer Thread
We can explore how to use a threading.Timer object with a worked example.
In this example we will use a timer to delay some processing, in this case to report a custom message after a wait period.
First, we can define a target task function that takes a message, then reports it with a print statement.
1 2 3 4 |
# target task function def task(message): # report the custom message print(message) |
Next, we can create an instance of the threading.Timer class. We will configure the Timer with a delay of 3 seconds, then call the task() function with a single argument message of ‘Hello world’.
1 2 3 |
... # create a thread timer object timer = Timer(3, task, args=('Hello world',)) |
Next, we can start the timer thread.
1 2 3 |
... # start the timer object timer.start() |
Finally, the main thread will wait for the timer thread to complete before exiting.
1 2 3 |
... # wait for the timer to finish print('Waiting for the timer...') |
Tying this together, the complete example is listed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# SuperFastPython.com # example of using a thread timer object from threading import Timer # target task function def task(message): # report the custom message print(message) # create a thread timer object timer = Timer(3, task, args=('Hello world',)) # start the timer object timer.start() # wait for the timer to finish print('Waiting for the timer...') |
Running the example first creates the threading.Timer object and specifies the target task() function with a single argument.
The timer is then started and the main thread waits for the timer thread to finish.
The timer thread runs, waits for the configured 3 seconds, then executes the task() function reporting the custom message.
1 2 |
Waiting for the timer... Hello world |
Next, let’s look at how we might cancel a timer thread object.
Free Python Threading Course
Download your FREE threading PDF cheat sheet and get BONUS access to my free 7-day crash course on the threading API.
Discover how to use the Python threading module including how to create and start new threads and how to use a mutex locks and semaphores
Example of Canceling a Timer Thread
In this section, we can explore how to cancel a timer thread before it is triggered.
The example in the previous section can be updated to cancel the timer and ensure the target task function is not executed.
This can be achieved by calling the cancel() function on the threading.Timer thread instance after the timer has been started.
1 2 3 4 |
... # cancel the thread print('Canceling the timer...') timer.cancel() |
Tying this together, the complete example is listed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# SuperFastPython.com # example of using a thread timer object from time import sleep from threading import Timer # target task function def task(message): # report the custom message print(message) # create a thread timer object timer = Timer(3, task, args=('Hello world',)) # start the timer object timer.start() # block for a moment sleep(1) # cancel the thread print('Canceling the timer...') timer.cancel() |
Running the example starts the timer thread with the target task() function to trigger in 3 seconds.
The main thread waits for a second, then cancels the timer thread, preventing the task() function from executing and the message from being reported.
1 |
Canceling the timer... |
Overwhelmed by the python concurrency APIs?
Find relief, download my FREE Python Concurrency Mind Maps
Further Reading
This section provides additional resources that you may find helpful.
Python Threading Books
- Python Threading Jump-Start, Jason Brownlee (my book!)
- Threading API Interview Questions
- Threading Module API Cheat Sheet
I also recommend specific chapters in the following books:
- Python Cookbook, David Beazley and Brian Jones, 2013.
- See: Chapter 12: Concurrency
- Effective Python, Brett Slatkin, 2019.
- See: Chapter 7: Concurrency and Parallelism
- Python in a Nutshell, Alex Martelli, et al., 2017.
- See: Chapter: 14: Threads and Processes
Guides
- Python Threading: The Complete Guide
- Python ThreadPoolExecutor: The Complete Guide
- Python ThreadPool: The Complete Guide
APIs
References
Takeaways
You now know how to use a threading.Timer object in Python.
Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.
Photo by Dominik Lalic on Unsplash
Do you have any questions?