In your code, you encounter a socket-related function call from an external module that occasionally blocks for unacceptable durations. You seek a solution to limit the execution time of this function call. A viable approach involves utilizing another thread.
A refined version of the accepted answer leverages the with statement to enhance the syntax of 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!")
By incorporating this code, you can manage time limits for function calls and effectively handle timeout exceptions.
The above is the detailed content of How Can I Implement a Time Limit for a Function Call to Prevent Blocking?. For more information, please follow other related articles on the PHP Chinese website!