[PYTHON] A decorator that does something if the function doesn't finish within the specified time

This is an improved version of the tips I posted yesterday. The part to be notified is separated by passing a handler function so that arbitrary processing can be performed.

I also tried using functools.wrap, which @methane taught me. I also tried a function with this decorator on paver's @task, but the help was None and the docstring didn't appear because I didn't use it! (I got a docstring in the help when I used functools.wrap)

timeout.py


from functools import wraps

def on_timeout(limit, handler, hint=None):
    '''                                                                                                    
If it does not finish in the specified execution time, hint handler/Call with limit as an argument
    @on_timeout(limit=3600, handler=notify_func, hint=u'Long calculation')                                         
    def long_time_function():                                                                              
    '''
    def notify_handler(signum, frame):
        handler("'%s' is not finished in %d second(s)." % (hint, limit))

    def __decorator(function):
        def __wrapper(*args, **kwargs):
            import signal
            signal.signal(signal.SIGALRM, notify_handler)
            signal.alarm(limit)
            result = function(*args, **kwargs)
            signal.alarm(0)
            return result
        return wraps(function)(__wrapper)
    return __decorator

The actual usage is as follows

main.py



from timeout import on_timeout

def handler_func(msg):
    print msg #Actually perform appropriate notification processing

@on_timeout(limit=1, handler=handler_func, hint=u'Long calculation')
def long_time_function():
    import time
    time.sleep (2)

if __name__ == "__main__":
    long_time_function()
 

When this is executed, the process is sleep (2) even though the limit is 1 second, so handler_func is called after 1 second, and the display is as follows.

'Long calculation' is not finished in 1 second(s).

With this, it seems that it can be applied to other than AWS.

Recommended Posts

A decorator that does something if the function doesn't finish within the specified time
A decorator that notifies you via AWS-SNS if the function does not finish within the specified time
A function that measures the processing time of a method in python
[Python3] Define a decorator to measure the execution time of a function
# Function that returns the character code of a string
What does the last () in a function mean in Python?
How to create a new file when the specified file does not exist — write if the file exists
Make a function decorator
Grep so that grep does not appear at the time of grep
I made a function to check if the webhook is received in Lambda for the time being