Timeout decorator
Sometimes it makes sense to end a method when a defined point in time is exceeded. The following code shows a decorator that will end any decorated function after the defined time.
import signal
TASK_TIMEOUT = 4
class Timeout(Exception):
pass
def timed_task(method):
def _handle_timeout(signum, frame):
raise Timeout("Task TIMEOUT! [{} Seconds]".format(TASK_TIMEOUT))
def timed(*args, **kw):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(TASK_TIMEOUT)
try:
result = method(*args, **kw)
finally:
signal.alarm(0)
return result
return timed
To use this we have just decorate a function and whait til the exception is thrown.
from time import sleep
from decorators.timed_task import timed_task, TASK_TIMEOUT
@timed_task
def sleepyhead():
sleep(TASK_TIMEOUT + 1)
sleepyhead()
The cool thing about this is the signal.alarm part. This function is able to call a so called handler after a defined period of time. In this case this is the method handle_timeout wich will raise the Timeout-Exception.
decorators.timed_task.Timeout: Task TIMEOUT! [5 Seconds]