Skip to content

Commit

Permalink
fix: remove gather from shutdown to prevent task destruction warning
Browse files Browse the repository at this point in the history
Previously, the shutdown process was using both sequential task awaiting and gather() to wait for task completion:

```python
for task in tasks:
    await task
await asyncio.gather(*tasks)
```

This created an issue where the gather() operation would create a new task that was being destroyed before completion, resulting in the warning: "Task was destroyed but it is pending!"

The fix simplifies the shutdown process by removing the redundant gather() call and only using sequential task awaiting. This ensures clean task  completion without creating additional tasks that could be destroyed during shutdown.

Also improved logging to better track the shutdown process and task completion status.
  • Loading branch information
aliev committed Dec 25, 2024
1 parent 5e8291b commit b71b58b
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
13 changes: 9 additions & 4 deletions aioshutdown/_shutdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,19 @@ async def shutdown(loop: asyncio.AbstractEventLoop, signal: Signals) -> None:
if t is not asyncio.current_task(loop=loop)
]

logger.info("Cancelling %d outstanding tasks", len(tasks))

# Request for cancellation of all outstanding tasks.
for task in tasks:
logger.info("Cancelling task: %s", task)
cancel(task, signal)

logger.info("Cancelling %d outstanding tasks", len(tasks))

# Concurrently wait for all tasks to be cancelled.
await asyncio.gather(*tasks, return_exceptions=True)
try:
await task
except asyncio.CancelledError as exc:
logger.info("Task %s cancelled with args: %s", task, exc.args)
except Exception:
logger.exception("Error while cancelling task %s", task)

logger.info("Stopping event loop")

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "aioshutdown"
version = "0.0.3"
version = "0.0.4"
description = "Context manager that provides simple graceful shutdown interface for your asyncio tasks."
requires-python = ">=3.8"
authors = [
Expand Down

0 comments on commit b71b58b

Please sign in to comment.