Created
November 8, 2022 16:46
-
-
Save inkychris/b2e033b6ad4be606cd5817b95c2141a8 to your computer and use it in GitHub Desktop.
Long running process that terminates on different (Windows compatible) signals
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 logging | |
import os | |
import signal | |
import sys | |
import time | |
import timeit | |
start_time = timeit.default_timer() | |
logger = logging.getLogger(__name__) | |
logger.setLevel(logging.DEBUG) | |
formatter = logging.Formatter('[%(process)d] %(asctime)s: %(message)s') | |
for handler in ( | |
logging.StreamHandler(sys.stdout), | |
logging.FileHandler(f'{os.environ.get("CI_BUILDS_DIR", ".")}/signal_handler.log') | |
): | |
handler.setLevel(logging.DEBUG) | |
handler.setFormatter(formatter) | |
logger.addHandler(handler) | |
logger.info('! ------- start ------- !') | |
for key in ('CI_PROJECT_ID', 'CI_PIPELINE_ID', 'CI_JOB_ID'): | |
logger.info(f'{key}={os.environ.get(key)}') | |
def signal_handler(signum, frame): | |
runtime = timeit.default_timer() - start_time | |
logger.info(f'terminated after {runtime:.1f}s with {signal.Signals(signum).name}') | |
exit(1) | |
for sig in (signal.SIGINT, signal.SIGABRT, signal.SIGSEGV, signal.SIGTERM): | |
signal.signal(sig, signal_handler) | |
logger.debug(sys.argv) | |
while True: | |
logger.debug(f'heartbeat: {timeit.default_timer() - start_time:.1f}') | |
time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment