Threading Timer Thread in Python

March 1, 2022 Python Threading

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?

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:

...
# 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.

...
# 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:

...
# 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.

# 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'.

...
# create a thread timer object
timer = Timer(3, task, args=('Hello world',))

Next, we can start the timer thread.

...
# start the timer object
timer.start()

Finally, the main thread will wait for the timer thread to complete before exiting.

...
# wait for the timer to finish
print('Waiting for the timer...')

Tying this together, the complete example is listed below.

# 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.

Waiting for the timer...
Hello world

Next, let's look at how we might cancel a timer thread object.

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.

...
# cancel the thread
print('Canceling the timer...')
timer.cancel()

Tying this together, the complete example is listed below.

# 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.

Canceling the timer...

Takeaways

You now know how to use a threading.Timer object in Python.



If you enjoyed this tutorial, you will love my book: Python Threading Jump-Start. It covers everything you need to master the topic with hands-on examples and clear explanations.