Home > Mobile >  call a time-sensitive fail-safe function
call a time-sensitive fail-safe function

Time:11-21

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") 

CodePudding user response:

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