Home > Article > Backend Development > How to Limit the Execution Time of a Blocking Function Call in Python?
Limiting Execution Time of a Function Call
You've encountered a socket-related function call in your code that exhibits occasional extended blocking, reaching hours at times. This poses an unacceptable situation. To mitigate this issue, you seek a solution within your code to limit the function's execution time.
As suggested in the accepted answer, employing another thread may provide a solution. However, an enhanced approach is to utilize the with statement, offering syntactic convenience for the timeout function:
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!")
This approach allows you to handle the timeout more elegantly within a block, raising a TimeoutException if the function exceeds the designated time limit.
The above is the detailed content of How to Limit the Execution Time of a Blocking Function Call in Python?. For more information, please follow other related articles on the PHP Chinese website!