Home  >  Article  >  Backend Development  >  How to Limit the Execution Time of a Blocking Function Call in Python?

How to Limit the Execution Time of a Blocking Function Call in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-24 03:02:12910browse

How to Limit the Execution Time of a Blocking Function Call in Python?

Limiting Execution Time of a Function Call

You've encountered a socket-related function call in your code that exhibits occasional extended blocking, reaching hours at times. This poses an unacceptable situation. To mitigate this issue, you seek a solution within your code to limit the function's execution time.

As suggested in the accepted answer, employing another thread may provide a solution. However, an enhanced approach is to utilize the with statement, offering syntactic convenience for 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!")

This approach allows you to handle the timeout more elegantly within a block, raising a TimeoutException if the function exceeds the designated time limit.

The above is the detailed content of How to Limit the Execution Time of a Blocking Function Call in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn