English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Timer object in Python

The timer object is used to create certain operations that are limited by time periods. Use timer objects to create some threads that perform certain operations. In Python, Timer is a subclass of Thread. Usestart()Method timer starts.

Create a Timer Object

threading.Timer(interval, function, args = None, kwargs = None), which is the syntax for creating a Timer object.

Firstly, in this example, we will get

Goodbye

3It will be displayed after seconds

Python Program

Example

import threading
   def mytimer():
      print("Python Program\n")
      my_timer = threading.Timer(3.0, mytimer)
      my_timer.start()
print("Bye\n")

Output Result

Bye
Python Program

Cancel Timer

The syntax of timer.cancel() is to cancel the timer.

Example

import threading
   def mytimer():
      print("Python Program\n")
      my_timer = threading.Timer(3.0, mytimer)
      my_timer.start()
   print("Cancelling timer\n")
      my_timer.cancel()
print("Bye\n")

Output Result

Cancelling Timer
Bye