Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions sanic/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -1882,7 +1882,10 @@ def purge_tasks(self) -> None:
}

def shutdown_tasks(
self, timeout: float | None = None, increment: float = 0.1
self,
timeout: float | None = None,
increment: float = 0.1,
loop: asyncio.AbstractEventLoop | None = None,
) -> None:
"""Cancel all tasks except the server task.

Expand All @@ -1897,6 +1900,8 @@ def shutdown_tasks(
to complete. Defaults to `None`.
increment (float): The amount of time to wait between checks for
whether the tasks have completed. Defaults to `0.1`.
loop (Optional[asyncio.AbstractEventLoop]): The event loop to use
for waiting. If not provided, attempts to get the running loop.
"""
for task in self.tasks:
if task.get_name() != "RunServer":
Expand All @@ -1905,10 +1910,17 @@ def shutdown_tasks(
if timeout is None:
timeout = self.config.GRACEFUL_SHUTDOWN_TIMEOUT

while len(self._task_registry) and timeout:
with suppress(RuntimeError):
running_loop = get_running_loop()
running_loop.run_until_complete(asyncio.sleep(increment))
if loop is None:
try:
loop = get_running_loop()
except RuntimeError:
loop = asyncio.get_event_loop()
Comment thread
ahopkins marked this conversation as resolved.
Outdated

while self._task_registry and timeout > 0:
try:
loop.run_until_complete(asyncio.sleep(increment))
except RuntimeError:
pass
Comment thread
ahopkins marked this conversation as resolved.
self.purge_tasks()
timeout -= increment

Expand Down
2 changes: 1 addition & 1 deletion sanic/server/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ def _cleanup():
loop.run_until_complete(asyncio.sleep(0.1))
start_shutdown = start_shutdown + 0.1

app.shutdown_tasks(graceful - start_shutdown)
app.shutdown_tasks(graceful - start_shutdown, loop=loop)

# Force close non-idle connection after waiting for
# graceful_shutdown_timeout
Expand Down
Loading