Timer objects in Python

Threading.timer class provides the timer functionality in Python. A function can be executed after the elapse of specified number of seconds using the timer class. The Python example executes a function at the elapse of 60 seconds.

Synchronization Updated 14 Sep 2018 1 min read

Overview

  • A timer helps in executing a set of instructions only after a specified amount of time has elapsed.
  • Python provides a timer object through threading.Timer class which is a subclass of threading.Thread class.
  • The constructor of the threading.Timer class takes a function and a time interval after which the function should be executed.
  • The timer class has a cancel method which can be used to stop the timer before it has started executing the timer function i.e.,while the timer is waiting for the specified time duration to elapse.
  • The timer class provided by Python threading module does not execute the timer function after every elapse of specified number of seconds. It just executes the timer function only once after the time elapse.

Example

python
import threading

def MinuteAlarm():

    print("Printing every minute")

minutely = threading.Timer(60, MinuteAlarm)

minutely.start()

Output

Output
Printing after a minute