Understanding the Python Timer Class with Examples

When we want to perform some operation or want our function to run after a certain amount of time, we make use of Python Timer class. Timer class is a subclass of the threading class. Technically, you can say that we create Timer objects when we want actions (functions) bounded by the time. 

 For example, suppose we want to organize a quiz, where the participant has to answer each question in 10 seconds. Here, we can create a timer that will run in the background, and meanwhile, the participant will be thinking about the answer. Now, let us understand how to create a timer object

Syntax of Timer Class in Python

If you have not understood what Timer class does, you can think of it in this way – A Timer Class calls a function after the specified number of seconds.  

To start a timer, we need to call the start()(just like normal threads), and to stop the timer while it is still in the background, we can call cancel()

To use the Timer class, we need to import threading class  

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

Parameters-  

Interval– The time (in seconds) you want to wait before calling the next function. It can either be in float or integer. For example, for 3 seconds, interval=3. 

Function – The function you want to call after the specified interval of time. 

A pervasive way to describe *args and **kwargs parameters is- create a timer object that runs the function with arguments’ args’ and keyword arguments’ kwargs’ after interval seconds have passed. Args should be in the form of a list and0 keyword args or kwargs in the form of a dictionary

Return Type- 

It just calls the function specified in the parameters. 

Methods in Timer class 

  1. start() – It signifies the beginning of execution of the timer. 
  2. Cancel ()– During the timer’s execution, if we want to stop it, we can call the cancel(). 

Creating a Timer Object 

a. Understanding the basics

To understand the Timer object’s working, let us create a very small program that will help us understand the basics of the class. 

# Importing the Timer subclass from the threading Class
from threading import Timer

# creating a basic function that will print "hello"
def hello():
    print ("hello, world")

# creating the object of the Timer subclass
# Here, 5 sec means that the execution of the function="hello" after 5 seconds
t = Timer(interval=5.0, function=hello)

# starting the execution
t.start() # after 30 seconds, "hello, world" will be printed
Output-
hello, world
python timer

You will better understand the functioning of the above program when you try to run it on your own system.

b. Using the cancel method

Let us see how to use the cancel() function of Timer class.

# Importing the Timer subclass from the threading Class
from threading import Timer

# creating a basic function that will print "hello"
def hello():
    print ("hello world")
    
# creating the object of the Timer subclass
# Here, 5 sec means that the execution of the function="hello" after 5 seconds
t = Timer(interval=5.0, function=hello)
    
# starting the execution
t.start() # after 30 seconds, "hello, world" will be printed

print("Execution begins")

# cancelling the execution of the 'hello' function
t.cancel()
print("END")
Execution begins 
END

c. How to use the ‘args’ parameter of the python timer class

When we need to give the arguments to the function that need to be called, we use the args parameter. We must give the args argument in an array.

import threading

# To take multiple inputs we can use *before the parameter.
def print_name(*names):
    # From the array of names pick one name and print it
    for name in names:
        print("Hello",name)

# In the args parameter, give an array of names 
t = threading.Timer(3, print_name,["Ashwini","Vandy","Arijit"])

# start the execution
t.start()
print("Execution begins...")
Execution begins...
Hello Ashwini
Hello Vandy
Hello Arijit

Now that we have talked a lot about time, as a bonus let us make a program which will act as a Countdown Timer.

Countdown Timer in python

Using the time module

# We will use the time module
import time

# Create a function that will print the time
def create_countdown_timer(time):
    print(time,"......")

time_in_sec=int(input("Please entert the time in seconds:"))

for times in range(time_in_sec):
    # call the function and pass the current time left
    create_countdown_timer(time_in_sec-times)
    # call the function in every 1 second.
    time.sleep(1)
    
print("Time is up")
Please entert the time in seconds:7
7 ......
6 ......
5 ......
4 ......
3 ......
2 ......
1 ......
Time is up

Using the Timer class of python

# We will use the time module
import time

from threading import Timer

# Create a function that will print the time
def create_countdown_timer(time):
    print(time,"......")

# Here you have to enter the time for which the timer will run
time_in_sec=int(input("Please enter the time in seconds:"))

# For the first time we will call the function manually
create_countdown_timer(time_in_sec) 

for times in range(1,time_in_sec): 
    # calling the Timer class every second
    t = Timer(1,create_countdown_timer,[str(time_in_sec-times)])
    t.start()
    time.sleep(1)
    
print("\n Time is up")
    
Please entert the time in seconds:10
10 ......
9 ......
8 ......
7 ......
6 ......
5 ......
4 ......
3 ......
2 ......
1 ......
Time is up

Must Read:

Conclusion

The timer is a subclass of the threading Class in python. If we want to run any function after a certain interval of time, we can use the python timer class. In the args parameter, which is None by default, we can specify the arguments we want to give to the callback method.

Try to run the programs on your side and let us know if you have any queries.

Happy Coding!

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments