Python Threading Timer

In Python, the threading module allows developers to create multiple threads in a single program, enabling parallel execution of multiple tasks. The threading module also provides a Timer class that can be used to schedule a task to run after a specified amount of time has elapsed. In This article, we are going to explain how to use threading.timer class to schedule tasks in the Python program.

Understanding the Threading Timer Class in the threading module, The Timer class provides a way to schedule a function to run after a specified amount of time has elapsed. The Timer class takes two arguments: the time delay (in seconds) and the function to be executed. When the Timer object is started, it waits for the specified time and then runs the specified function.

Syntax:

In the above syntax, the delay is the time delay in seconds, and the function is the function to be executed.

Once the Timer object is created, the programmer can start it using the start() method. The Timer object will then run the specified function after the specified delay.

Example 1: A Simple Timer

Below is an example of a simple Timer that prints a message after a specified delay:

Code

Output:

Python Threading Timer

Explanation:

After the code runs successfully, it will wait 5 seconds and then print "Hello, world!" to the console. This is because the print_message() function is scheduled to be called by the Timer thread after a delay of 5 seconds.

Example 2: Repeating Timers

The Timer class can also be used to create repeating timers that execute a function at fixed intervals. To create a repeating timer, the programmer can use the Timer class along with the while loop. Below is an example of a Timer that repeats a function call every 2 seconds:

Code

Output:

Python Threading Timer

NOTE: It Continuously prints "Hello, world!" every 2 seconds until the program is manually terminated.

Explanation

The above code starts by creating a Timer object t with a delay of 2 seconds (i.e., threading.Timer(2.0, print_message)). This means that after 2 seconds, the print_message() function will be executed in a separate thread.

Then The while loop starts, and within the loop, the t timer is started using t.start(), which schedules the print_message() function to run after a delay of 2 seconds. The t.join() call blocks the main thread until the print_message() function finishes executing.

After the print_message() function completes, a new Timer object is created and assigned to t with the same 2-second delay. This creates a loop that keeps scheduling the print_message() function to run every 2 seconds indefinitely until the program is manually terminated.

The if not threading.active_count() > 1: it is a check condition used to break out of the loop and terminate the program when there are no more active threads other than the main thread. This is done to prevent the program from running indefinitely and causing a never-ending loop of "Hello, world!" messages.

Example 3: Canceling Timers

Sometimes the programmer may want to cancel a Timer before it has completed its delay. In that situation, the programmer can do this using the cancel() method of the Timer object. Here is an example of a Timer that is canceled before it can execute its function:

Code

Output

No output will be printed as the timer is canceled before it can execute

Explanation

The above code creates a Timer object from the threading module, which is a class that allows scheduling a function to run after a certain delay. The Timer is initialized with a delay of 5.0 seconds, and the print_message() function is the function to be executed.

After starting the timer with t.start(), the timer will wait for 5.0 seconds and then execute the print_message() function, which simply prints "Hello, world!".

However, immediately after starting the timer, t.cancel() is called, which cancels the timer before it can execute the function. As a result, no output will be printed, and the program will terminate without any further action.

Benefits of Timer Threading

The Python threading.Timer class provides several benefits to developers who need to schedule tasks in their Python programs:

  1. Asynchronous Execution: Using the Timer class, the programmer can schedule tasks to run asynchronously, allowing the program to continue executing while the task runs in the background.
  2. Precise Timing: The Timer class allows the programmer to execute tasks at precise intervals, making it useful for applications that require timing accuracy.
  3. Repeating Timers: The Timer class can be used to create repeating timers that execute a function at fixed intervals, eliminating the need for repetitive coding.
  4. Cancellation: The Timer class provides a way to cancel a Timer before it has completed its delay, providing greater control over your application's timing logic.

Disadvantages of Python Threading Timer

There are also some disadvantages to using a python threading timer. These are as follows.

  1. Resource Usage: a new thread is created when we try to create a new Timer object creates, which can consume system resources. If the programmer has many Timers running simultaneously, it can impact the program's performance and memory usage.
  2. Limited Precision: The Timer class relies on the system clock, which may not provide the precision required for certain applications. For example, if the application requires sub-millisecond timing accuracy, the Timer class may not be sufficient.
  3. Complexity: While the Timer class is relatively easy to use for simple cases, it can become complex when used for more complex timing scenarios. Proper use of control structures like loops is necessary to create complex scheduling logic.
  4. Debugging: Debugging threaded programs can be challenging. Debugging a program that uses the Timer class can be especially difficult if the programmer is not familiar with how the Timer class works.

Conclusion

Python's threading module provides a powerful way to create multiple threads in a single program, enabling parallel execution of multiple tasks. The Timer class in the threading module is a useful tool for scheduling tasks to run after a specified delay. Using the Timer class, loops, and other control structures, the programmer can create complex scheduling logic that executes functions at precise intervals.


Next TopicPython TOML




Latest Courses