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

Time:07-10

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

CodePudding user response:

I'd suggest doing some research on Thread, this could help. For your example, this might be what you're looking for:

from time import sleep
from threading import Thread


def fun_1(sleep_time, message):
    sleep(sleep_time)
    print(message)


def fun_2():
    # create a thread
    thread = Thread(target=fun_1, args=(2, 'Be kind : ) '))
    # run the thread
    thread.start()
    print(" Be Honest ")
    print("After 2 secs")
    thread.join()

fun_2()

CodePudding user response:

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()
  • Related