call a time-sensitive fail-safe function

Question:

I have a time-sensitive request, let’s call it query_response.

How to write the program so that, if query_response take less than 2 seconds then run take_action else run abort_action.

def query_response():
  print("Query Response")

def take_action():
  print("Take Action") 

def abort_action():
  print("Abort Action") 
Asked By: Ahmad Ismail

||

Answers:

So basically what you can do is save the time that your function started at and subtract the start_time from the time that your function ended at. For example: if your query_response started 12:34 and ended 12:37, you would get an execution time of 3 minutes. Code:

import time

def query_response():
  start_time = time.time() # Save the time your function started
  print("Query Response")
  time_passed = time.time() - start_time # Save the total execution time
                                         # of your function
  if time_passed > 2: take_action()
  else: abort_action()

def take_action():
  print("Take Action") 

def abort_action():
  print("Abort Action")
Answered By: MarshiDev
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.