Timer objects in Python


In Python, Timer is a subclass of Thread class. Calling the start() method, the timer starts. Timer objects are used to create some actions which are bounded by the time period. Using timer object create some threads that carries out some actions. The Timer is stopped using the cancel() method.

How to create a Timer object

Following is how you can create a Timer object in Python −

threading.Timer(interval, function, args = None, kwargs = None)

Starting a Timer

The timer.start() is used for start the timer. Here’s an example −

Example

import threading # All the text displays after 3 seconds def mytimer(): print("Demo Python Program\n") my_timer = threading.Timer(3.0, mytimer) my_timer.start() print("Bye\n")

Output

Bye

Demo Python Program

Cancelling a Timer

The timer.cancel() is used for cancelling the timer. Here’s an example −

Example

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

Output

Cancelling timer

Bye

Updated on: 12-Aug-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements