Skip to content

Instantly share code, notes, and snippets.

@justinnaldzin
Last active March 7, 2017 18:24
Show Gist options
  • Save justinnaldzin/235890460094b9d31574833d7fc979c2 to your computer and use it in GitHub Desktop.
Save justinnaldzin/235890460094b9d31574833d7fc979c2 to your computer and use it in GitHub Desktop.
Python 'Timeout' class that will raise an exception after the containing code does not finish within a specified number of seconds. Use the 'retry' decorator to retry the function a specified number of times after the timeout. NOTE: this works for Unix only. Additionally, signal only works in main thread.
import time
import signal
from retrying import retry
class Timeout:
def __init__(self, seconds=1, error_message='Timeout'):
self.seconds = seconds
self.error_message = error_message
def handle_timeout(self, signum, frame):
raise TimeoutError(self.error_message)
def __enter__(self):
signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, type, value, traceback):
signal.alarm(0)
@retry(stop_max_attempt_number=6) # stop after 6 attempts
def long_running_function():
with Timeout(seconds=5):
print("Doing something that takes a while...")
time.sleep(10)
long_running_function()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment