Threading Timer Thread in Python - Super Fast Python

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.


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

Learn more
 


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.

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.

Further Reading

This section provides additional resources that you may find helpful.

Python Threading Books

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

APIs

References


Python Threading Jump-Start

Loving The Tutorials?

Why not take the next step? Get the book.

Learn more
 


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