Topics

Timer Object

Welcome to a tutorial on Timer Object in Python Multithreading. In Python, Timer objects are created using the Timer class which is typically a subclass of the Thread class. While using this class, a delay on any action can be set that should be run only after a certain amount of time has passed (or timer) and can be canceled easily during that delay.

A Timer is started, and is similar to normal threads, by calling their start() method. Also, a timer thread can be stopped (before its action has begun) by calling its cancel() method.

A timer object is generally used to implement scheduled tasks that are supposed to be executed after a certain instant of time only.

 

Syntax for creating Timer object

Below is the syntax for the Timer class constructor:

threading.Timer(interval, function, args=[], kwargs={})

From above, we can create a timer object that will run the function with arguments args and keyword arguments kwargs, after interval seconds have passed.

 

Methods of Timer class

In the Timer class, there are two methods for starting and canceling the execution of the timer object.

 

start() method

The start() method is used to start the execution of the timer object. When this method is called, the timer object starts its timer.

 

cancel() method

The cancel() method is used to stop the timer and cancel the execution of the timer object's action, but this can work only if the timer has not yet performed its action.

 

Let’s try some Example

In this example, we will create a timer object and start it.

import threading

def task():
    print("timer object task running...")

if __name__=='__main__':
    t = threading.Timer(10, task)
    t.start() # after 10 seconds, task will be executed

The code is a very simple one, we used the cancel method to cancel the timer object task’s execution.

import threading
import time

def task():
  print("Timer object is getting executed...")

if __name__=='__main__':
  t = threading.Timer(5, task)
  print("Starting the timer object...")
  t.start() # after 5 seconds, task will be executed
  
  # cancelling the timer object before start
  print("cancelling the timer object")
  t.cancel()

Output:

Starting the timer object...
cancelling the timer object

The code is a very simple one, we used the cancel method to cancel the timer object task’s execution.