Skip to content

Instantly share code, notes, and snippets.

@monsterxx03
Last active May 28, 2020 09:34
Show Gist options
  • Save monsterxx03/6916989 to your computer and use it in GitHub Desktop.
Save monsterxx03/6916989 to your computer and use it in GitHub Desktop.
timeout
import time
import signal
class death_penalty_after(object):
def __init__(self, timeout):
self.timeout = timeout
def __enter__(self):
# register alarm siganl to handler
signal.signal(signal.SIGALRM, self.handle_death_penalty)
signal.alarm(self.timeout)
def handle_death_penalty(self, signum, frame):
# use exception to stop executing jobs
raise Exception('timeout')
def __exit__(self, exec_type, exc_value, exc_tb):
# remove alarm signal
signal.alarm(0)
with death_penalty_after(3):
time.sleep(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment