Timed Out Functions: How to Limit Execution Time
In shell scripts, it can be beneficial to prevent certain functions from executing endlessly, especially when it involves accessing remote resources like URLs. By setting timeouts, you can ensure that functions don't freeze your script due to slow or unresponsive servers.
One method of implementing timeouts is to utilize the signal module's timeout decorator. This decorator, described in the signal documentation, uses signal handlers to set an alarm. Once the specified time interval passes, an exception is raised, effectively stopping the function.
To use the timeout decorator, import it from the timeout.py module and specify the timeout duration (in seconds) as an argument. Below is an example snippet that creates a decorator with a default timeout of 10 seconds and a custom error message:
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
To use the decorator, simply apply it to your long-running function, like in the following examples:
# Default timeout of 10 seconds @timeout def long_running_function1(): ... # Timeout of 5 seconds @timeout(5) def long_running_function2(): ... # Timeout of 30 seconds, with custom error message 'Connection timed out' @timeout(30, os.strerror(errno.ETIMEDOUT)) def long_running_function3(): ...
Remember that this implementation is only applicable on UNIX systems. By implementing timeouts using the signal module's decorator, you now have control over the execution duration of your functions and prevent them from holding up your shell script unnecessarily.
The above is the detailed content of How Can I Prevent Shell Script Functions from Timing Out When Accessing Remote Resources?. For more information, please follow other related articles on the PHP Chinese website!