Home > Backend Development > Python Tutorial > How Can I Implement a Time Limit for a Function Call to Prevent Blocking?

How Can I Implement a Time Limit for a Function Call to Prevent Blocking?

Susan Sarandon
Release: 2024-11-22 09:24:15
Original
275 people have browsed it

How Can I Implement a Time Limit for a Function Call to Prevent Blocking?

Implementing a Time-Limited Function Execution

In your code, you encounter a socket-related function call from an external module that occasionally blocks for unacceptable durations. You seek a solution to limit the execution time of this function call. A viable approach involves utilizing another thread.

A refined version of the accepted answer leverages the with statement to enhance the syntax of 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!")
Copy after login

By incorporating this code, you can manage time limits for function calls and effectively handle timeout exceptions.

The above is the detailed content of How Can I Implement a Time Limit for a Function Call to Prevent Blocking?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template