How Can I Implement Time Limits for Blocking Function Calls in Python?

Susan Sarandon
Release: 2024-11-20 02:20:01
Original
929 people have browsed it

How Can I Implement Time Limits for Blocking Function Calls in Python?

Implementing Time Limits for Function Calls

In certain scenarios, a function call in your code may block unexpectedly, causing unacceptable delays. This issue arises when the function originates from an external module, leaving you with limited control over its execution. To address this problem, it is essential to introduce a time limit on the function's runtime.

One effective solution involves employing another thread. By using a timeout function, you can specify a maximum execution duration for the original function call. If this time limit is exceeded, an exception is raised, enabling you to handle the situation gracefully.

The following improved implementation provides a clear and concise approach using the with statement:

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 utilizing this technique, you can effectively limit the execution time of function calls, preventing excessive delays and ensuring a controlled and responsive application.

The above is the detailed content of How Can I Implement Time Limits for Blocking Function Calls in Python?. 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