Last active
December 8, 2017 18:03
-
-
Save loisaidasam/6793b8c4b9e8879ccddfe4bd4a2374a0 to your computer and use it in GitHub Desktop.
Gracefully handling SIGTERM
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
"""Gracefully handling SIGTERM | |
References: | |
- https://stackoverflow.com/questions/18499497/how-to-process-sigterm-signal-gracefully/31464349#31464349 | |
- https://devcenter.heroku.com/articles/dynos#shutdown | |
""" | |
import logging | |
import signal | |
import time | |
logger = logging.getLogger(__name__) | |
logger.setLevel(logging.INFO) | |
stream_handler = logging.StreamHandler() | |
stream_handler.setLevel(logging.INFO) | |
logger.addHandler(stream_handler) | |
class SignalCatcher(object): | |
caught_signal = False | |
def __init__(self): | |
""" | |
TODO: Should we catch anything else?? | |
""" | |
signal.signal(signal.SIGINT, self.handle_signal) | |
signal.signal(signal.SIGTERM, self.handle_signal) | |
def handle_signal(self, signum, frame): | |
logger.warning("SignalCatcher caught signum `%s`", signum) | |
self.caught_signal = True | |
catcher = SignalCatcher() | |
def do_stuff(): | |
logger.info("Doing stuff!") | |
while True: | |
logger.info("Doing some stuff in a loop!") | |
time.sleep(3) | |
if catcher.caught_signal: | |
logger.info("I got killed gracefully! Finishing up some stuff ...") | |
time.sleep(2) | |
break | |
logger.info("Done!") | |
def main(): | |
try: | |
do_stuff() | |
except Exception as e: | |
logger.exception("Caught exception! %s", e) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment