Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gracefully handling SIGTERM
"""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
You can’t perform that action at this time.