Implementing Time Limits for Function Calls
In certain scenarios, a function call in your code may block unexpectedly, causing unacceptable delays. This issue arises when the function originates from an external module, leaving you with limited control over its execution. To address this problem, it is essential to introduce a time limit on the function's runtime.
One effective solution involves employing another thread. By using a timeout function, you can specify a maximum execution duration for the original function call. If this time limit is exceeded, an exception is raised, enabling you to handle the situation gracefully.
The following improved implementation provides a clear and concise approach using the with statement:
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 utilizing this technique, you can effectively limit the execution time of function calls, preventing excessive delays and ensuring a controlled and responsive application.
The above is the detailed content of How Can I Implement Time Limits for Blocking Function Calls in Python?. For more information, please follow other related articles on the PHP Chinese website!