Cancelling Long-Running Function Calls with Timeouts
When executing complex scripts that include potentially stalling functions, it is desirable to provide a way to terminate these functions if they exceed a specified execution time. This ensures that the script does not become unresponsive or remain indefinitely stuck.
In Python, leveraging the signal package (available on UNIX systems) offers a solution for this problem. By registering a signal handler, you can set a timeout for a function call. If the function takes longer than the specified time, the handler is invoked, allowing you to handle the situation appropriately.
Consider the following code snippet:
import signal # Register a signal handler for the timeout def handler(signum, frame): print("Forever is over!") raise Exception("end of time") # Define a function that may run for an indetermined time def loop_forever(): import time while 1: print("sec") time.sleep(1) # Register the signal function handler signal.signal(signal.SIGALRM, handler) # Define a timeout for the function signal.alarm(10) try: loop_forever() except Exception as exc: print(exc) # Cancel the timer if the function returned before timeout signal.alarm(0)
In this example, we register the handler function to handle the timeout signal. We then define our long-running loop_forever function, which continuously prints the message "sec" every second.
After setting a 10-second timeout using signal.alarm(10), we attempt to execute loop_forever. If the function takes longer than 10 seconds to execute, our signal handler is invoked, printing "Forever is over!" and raising an exception.
To ensure proper handling of the timeout scenario, it is essential to cancel the timer if the function returns before the specified time. In our example, we call signal.alarm(0) to cancel the timer when the exception is raised.
Note that the signal package may not interact well with multi-threaded environments. Additionally, if a function catches and ignores exceptions raised during timeout, the timeout mechanism may not be effective.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3