Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit execution time of a function call?

There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.

like image 927
btw0 Avatar asked Dec 14 '08 16:12

btw0


People also ask

How do you limit the execution time of a function in Python?

You can limit the execution time of a function by using the signal library.

How do you set time limits in Python?

You can use the time. time() function. It returns the time since Jan 1st 1970 in seconds! So, you can just do this : import time b = True #declare boolean so that code can be executed only if it is still True t1 = time.

How do you stop a function from running in Python?

To stop code execution in python first, we have to import the sys object, and then we can call the exit() function to stop the program from running. It is the most reliable way for stopping code execution. We can also pass the string to the Python exit() method.

How do you get out of a function execution?

Using return is the easiest way to exit a function. You can use return by itself or even return a value.


1 Answers

An improvement on @rik.the.vik's answer would be to use the with statement to give the timeout function some syntactic sugar:

import signal from contextlib import contextmanager  class TimeoutException(Exception): pass  @contextmanager def time_limit(seconds):     def signal_handler(signum, frame):         raise TimeoutException("Timed out!")     signal.signal(signal.SIGALRM, signal_handler)     signal.alarm(seconds)     try:         yield     finally:         signal.alarm(0)   try:     with time_limit(10):         long_function_call() except TimeoutException as e:     print("Timed out!") 
like image 165
Josh Lee Avatar answered Oct 13 '22 03:10

Josh Lee