Home > Backend Development > Python Tutorial > How to Implement a Timeout Function to Prevent Long-Running Processes?

How to Implement a Timeout Function to Prevent Long-Running Processes?

Barbara Streisand
Release: 2024-11-30 08:55:15
Original
895 people have browsed it

How to Implement a Timeout Function to Prevent Long-Running Processes?

Timeout Function if it Takes Too Long to Finish

In order to avoid a situation where a specific function takes too long to finish, a timeout mechanism can be implemented. This involves setting an alarm using signal handlers that will raise an exception after a predetermined period of time. This method is particularly useful for UNIX environments.

Here's how to utilize this mechanism:

  1. Create a Decorator:
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
Copy after login
  1. Apply the Decorator:
from timeout import timeout

# Timeout a long running function with the default expiry of 10 seconds.
@timeout
def long_running_function():
    ...

# Timeout after 5 seconds
@timeout(5)
def another_long_running_function():
    ...
Copy after login

This ensures that any function decorated with @timeout will be interrupted if it exceeds the specified timeout period.

The above is the detailed content of How to Implement a Timeout Function to Prevent Long-Running Processes?. 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