I'm trying to write a service that run a task periodically. That task could take could take longer than the sleep time so it will start an other task in a pool. The thing is, because it's a service I'll like to be able to stop it. So it need to handle a SIGTERM. Here's what what I have got so far:
def test_task():
task_id = random.randint(1000, 9999)
logger = CustomLogger()
for i in range(5):
text = f"({task_id}) timestamp: {str(datetime.now())}"
logger.out(text)
time.sleep(SLEEP_TIME)
logger.out(f"task ({task_id}) done")
class TestService:
def __init__(self):
signal.signal(signal.SIGTERM, self._handle_sigterm)
signal.signal(signal.SIGINT, self._handle_sigterm)
self.logger = CustomLogger()
self.pool = Pool(processes=12)
def start(self):
while True:
self.pool.apply_async(test_task)
time.sleep(2)
def _handle_sigterm(self, sig, frame):
self.logger.out("signal handled")
self._stop()
def _stop(self):
self.pool.join()
sys.exit(0)
When I try to terminate it, I terminate all my subprocess and I don't know why
I tryed many things, like unsing contexte, try to send an event, have a custom process for my task but not luck. What I'll like to see it's when it receive the signal it wait that all subprocess dies then exit cleanly.