How to call a function after some interval in Python

In this tutorial, we will learn how to call a function after some interval in Python. We will use threading.Timer(delay,fun) here.

The most common word while programming is “Function”.

A Function is a set of statements, written to perform specific operations.

Certainly, it would be clear with an example.

Sample Function :

def sample_function(number):         # user defined function which adds +10 to given number
    
    return number+10
    


num = 45

add_num = sample_function(num)         # calling a function

print ("After adding 10 to",num,"the result is :",add_num)
Output :

After adding 10 to 45 the result is: 55

It would be crystal clear about how a function works in Python.

Call a function after some interval in Python

Moreover, moving on to applying time delay to call a function, there are some key-points,

  • A timer applies the desired delay.
  • Python has timer objects that provide the facility to give arguments.
  • The timer is basically a subclass of the Thread class.
  • timer.start( ) starts the timer and schedules the task.

Steps to perform the time delay to call a function :

import threading

Don’t worry, that module is inbuilt and no extra code is necessary to import that.

This is the class that consists of a subclass called timer.

Now, writing user-defined function:

def fun():         # user defined function which adds +10 to given number
    
    print ("Hey u called me")
    

This function will get called after a certain delay in time.

Moreover, it is necessary to write the function definition above function call.

import threading 


def fun():         # user defined function which adds +10 to given number
    
    print ("Hey u called me")
    



delay = int(input("Enter the delay time :"))

start_time = threading.Timer(delay,fun)

start_time.start()

print ("End of the code")
Output :

Enter the delay time : 5
End of the code
Hey u called me

Certainly, to grasp the code above these points will help,

  1.  delay = number of seconds after the function is called
  2.  start_time is a timer object that has the arguments of delay_time and function itself.
  3. .start( ) starts the timer.
  4. Certainly, the output clearly determines that the code below gets executed first.
  5. Moreover, exactly after 5 seconds of delay, the function gets executed.

Note : 

Syntax of threading.Timer : [ threading.Timer ( delay_time , function ) ]

Concluding, in programming the delays might be of use while Parallel Processing.

Also, read:

Leave a Reply

Your email address will not be published.