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.

2
  • Define "will be stuck" Commented Jun 17, 2020 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. Commented Jun 17, 2020 at 19:06

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.