Skip to content

Instantly share code, notes, and snippets.

@funollet
Created September 27, 2014 11:36
Show Gist options
  • Save funollet/d9dca9f1592b6a95c0b1 to your computer and use it in GitHub Desktop.
Save funollet/d9dca9f1592b6a95c0b1 to your computer and use it in GitHub Desktop.
Proof of concept: handle TERM signal but finish a job if it's already started
#!/usr/bin/python -u
# closer.py
#
# Just a trivial demo that handlers a TERM signal to exit cleanly, while still finishing
# any job that could have been running.
import signal
import sys
import time
JOB_COUNT = 0
STOP_FLAG = False
def stop(signum, stack):
"""Doesn't really stop now: just set a mark.
"""
global STOP_FLAG
STOP_FLAG = True
# Call function stop() when killed.
signal.signal(signal.SIGTERM, stop)
def get_job():
"""Just a dirty counter, returns incremental job ids.
"""
global JOB_COUNT
JOB_COUNT += 1
return JOB_COUNT
def do_job(job_id):
"""Run your job here.
"""
print "Job #{} started".format(job_id),
for i in range(20):
print '.',
time.sleep(.1)
print "Job #{} finished".format(job_id)
return
while True:
if STOP_FLAG:
# Don't take more jobs, just exit.
sys.exit(0)
else:
# Process another job.
job_id = get_job()
do_job(job_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment