0

Currently I am writing a function that includes random samples with some restrictions. It is possible at the last step there is no valid condition to choose and my function will be stuck.

Is there a way to set run time limit for this function? Let's say after 2 seconds, if there is no result returned, and it will run the function again until it returns the result within 2 seconds. Thanks in advance.

  • Define "will be stuck" – OneCricketeer Jun 17 '20 at 19:06
  • Could we see the code you've written so far? The easiest solution is probably going to be to check a stopwatch within the function, but it's hard to explain how to do it without having the existing code as an example. The other option would be to run the function on another thread and terminate it after a timeout. – Samwise Jun 17 '20 at 19:06

1 Answers1

1

You can use the threading module.

The following code is an example of a Thread with a timeout:

from threading import Thread

p = Thread(target = myFunc, args = [myArg1, myArg2])
p.start()
p.join(timeout = 2)

You could add something like the following to your code, as a check to keep looping until the function should properly end:

shouldFinish = False
def myFunc(myArg1, myArg2):
    ...
    if finishedProperly:
        shouldFinish = True

while shouldFinish == False:
    p = Thread(target = myFunc, args = [myArg1, myArg2])
    p.start()
    p.join(timeout = 2)
Xiddoc
  • 3,369
  • 3
  • 11
  • 37