Timeout Function if it Takes Too Long to Finish
In order to avoid a situation where a specific function takes too long to finish, a timeout mechanism can be implemented. This involves setting an alarm using signal handlers that will raise an exception after a predetermined period of time. This method is particularly useful for UNIX environments.
Here's how to utilize this mechanism:
import errno import os import signal import functools class TimeoutError(Exception): pass def timeout(seconds=10, error_message=os.strerror(errno.ETIME)): def decorator(func): def _handle_timeout(signum, frame): raise TimeoutError(error_message) @functools.wraps(func) def wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(seconds) try: result = func(*args, **kwargs) finally: signal.alarm(0) return result return wrapper return decorator
from timeout import timeout # Timeout a long running function with the default expiry of 10 seconds. @timeout def long_running_function(): ... # Timeout after 5 seconds @timeout(5) def another_long_running_function(): ...
This ensures that any function decorated with @timeout will be interrupted if it exceeds the specified timeout period.
The above is the detailed content of How to Implement a Timeout Function to Prevent Long-Running Processes?. For more information, please follow other related articles on the PHP Chinese website!