more context manager work

This commit is contained in:
John Lancaster
2024-10-20 21:27:51 +00:00
parent 8064a73e9f
commit 050fe75e71
2 changed files with 9 additions and 19 deletions

View File

@@ -36,9 +36,6 @@ class AppDaemonRunContext:
for s in signals:
self.loop.add_signal_handler(s, lambda s=s: self.loop.create_task(self.shutdown(s)))
# self.loop.add_signal_handler(signal.SIGINT, self.handle_signal, signal.SIGINT)
# self.loop.add_signal_handler(signal.SIGTERM, self.handle_signal)
# self.executor = self._stack.enter_context(ThreadPoolExecutor(max_workers=5))
self.executor = self._stack.enter_context(self.thread_context())
logger.debug("Entered threadpool context")
return self
@@ -56,22 +53,15 @@ class AppDaemonRunContext:
if not self.stop_event.is_set():
logger.debug('Setting stop event')
self.stop_event.set()
tasks = [
t for t in asyncio.all_tasks()
graceful = (
asyncio.wait_for(t, timeout=2.0)
for t in asyncio.all_tasks()
if t is not asyncio.current_task()
]
)
logger.debug('Allowing graceful shutdown from stop event')
await asyncio.gather(*graceful, return_exceptions=True)
for task in tasks:
# logger.debug(f"Waiting on task to finish: {task.get_coro().__qualname__}")
logger.debug(f"Cancelling {task.get_name()}: {task.get_coro().__qualname__}")
task.cancel()
logger.debug('Waiting for tasks to finish...')
try:
await asyncio.gather(*tasks, return_exceptions=True)
except asyncio.CancelledError as e:
logger.debug(f'Cancelled: {e}')
logger.debug("Stopping event loop in context shutdown")
self.loop.stop()
else: