Search code examples
pythonpython-3.xtimereturn-valuebreak

how to stop a func from running and return a value after one minute?


I would like to call a func and stop it from running after one minute, returning a value. i have a code that looks similar to that:

def foo(txt):
   best_value=-1
   for word in txt:
       if value(word)>best_value:
           best_value=value(world)
    return best_value

i would like to stop running after one minute and return best_value. thanks for your help.


Solution

  • If you want to decouple the timing code from the business logic and to keep the overhead to a minimum, an easy way is to use a global variable in the code to tell it when to stop running:

    time_out = False
    
    def foo(txt):
       best_value=-1
       for word in txt:
           if value(word)>best_value:
               best_value=value(world)
           if time_out:
               break
        return best_value
    

    Then use a separate function tied to use a Timer to stop it:

    def send_stop():
        global time_out
        time_out = True
    
    Timer(60.0, send_stop).start() 
    best_value = foo(corpus)