Search code examples
pythonmultithreadingpython-multithreadinghelper

How to make a function executes after x seconds of its call using python


I don't want function to be called every x secs I want a function to be executed after some seconds of its call and rest of program executes in order.

Like in my code I want to call fun_2() in which fun_1() is called which will make separate thread which will come live after x secs and in mean while fun_2() will print the statement then fun_1() will print its statement.

My Code:

import time

def fun_1(tim): # make this to be executed in separated thread 
  time.sleep(tim)
  print("Be kind : ) ")

def fun_2():
  fun_1(2) #Its call
  print(" Be Honest ")
  print("After 2 secs")
fun_2()

output should be like this

output


Solution

  • You don't need to write any code at all. That's exactly what the standard Python library's threading.Timer does. All you have to do is call it.

    import threading
    
    def fun_1(): # this will be executed in a separate thread 
      print("Be kind : ) ")
    
    def fun_2():
      threading.Timer(2.0, fun_1).start()
      print(" Be Honest ")
      print("After 2 secs")
    
    fun_2()