Last active
May 28, 2020 09:34
-
-
Save monsterxx03/6916989 to your computer and use it in GitHub Desktop.
timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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