NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior85 views

Вы хорошо описали управление задачами и корректное завершение. А как вы контролируете незавершённые операции AsyncIO при остановке приложения?

Practice

Asked at

AI answer

When shutting down an application, I first stop accepting new work, then cancel the current tasks or let them finish, and make sure to wait for their results. I usually keep references to background Task objects rather than creating them without tracking them.

tasks = set()

def spawn(coro):
    task = asyncio.create_task(coro)
    tasks.add(task)
    task.add_done_callback(tasks.discard)
    return task

async def shutdown():
    pending = list(tasks)
    for task in pending:
        task.cancel()
    results = await asyncio.gather(*pending, return_exceptions=True)

Coroutines should handle asyncio.CancelledError correctly: release resources in finally and usually propagate the cancellation further. If operations need to finish gracefully, give them a limited amount of time using asyncio.wait/wait_for, then cancel any that remain after the timeout. Also close clients, pools, and other resources, for example by using async with. Do not suppress cancellation indiscriminately or leave background tasks unawaited: this leads to leaks, warnings, and unfinished work.