Skip to content

Instantly share code, notes, and snippets.

@vadimg
Created June 9, 2012 22:16
Show Gist options
  • Save vadimg/2902788 to your computer and use it in GitHub Desktop.
Save vadimg/2902788 to your computer and use it in GitHub Desktop.
python timeout decorator
import threading
import functools
import logging
def timeout(duration, default=None):
def decorator(func):
class InterruptableThread(threading.Thread):
def __init__(self, args, kwargs):
threading.Thread.__init__(self)
self.args = args
self.kwargs = kwargs
self.result = default
self.daemon = True
def run(self):
try:
self.result = func(*self.args, **self.kwargs)
except Exception:
pass
@functools.wraps(func)
def wrap(*args, **kwargs):
it = InterruptableThread(args, kwargs)
it.start()
it.join(duration)
if it.isAlive():
logging.warning('timeout in function {0}: args: {1}, kwargs: {2}'.format(func, args, kwargs))
return it.result
return wrap
return decorator
@bitranox
Copy link

bitranox commented May 4, 2019

this does not work really - threads can not be interrupted.
The thread continues to run in the Background, wasting Memory and CPU, blocking probably other devices (Network, etc ...)
You need to use a process for that, check out : https://github.com/bitranox/wrapt_timeout_decorator
Yours sincerely
Robert

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment