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