Python threading Timer Class

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

  1. Introduction
  2. threading.Timer Class Syntax
  3. Examples
    • Basic Usage
    • Using Timer with Arguments
    • Stopping a Timer
  4. Real-World Use Case
  5. 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.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare