From 0b726398d2135ab414374412fa85f791569e3640 Mon Sep 17 00:00:00 2001 From: Numerlor <25886452+Numerlor@users.noreply.github.com> Date: Sat, 12 Jun 2021 16:07:24 +0200 Subject: Add an optional loop kwarg to scheduling.create_task Before this change, the create_task util couldn't be used to schedule tasks from the init of cogs, as it relied on asyncio.create_task that uses the currently running loop to create the task. The loop kwarg allows the caller to pass the loop itself if there's no running loop yet. --- bot/utils/scheduling.py | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/bot/utils/scheduling.py b/bot/utils/scheduling.py index 2dc485f24..b99874508 100644 --- a/bot/utils/scheduling.py +++ b/bot/utils/scheduling.py @@ -161,9 +161,21 @@ class Scheduler: self._log.error(f"Error in task #{task_id} {id(done_task)}!", exc_info=exception) -def create_task(coro: t.Awaitable, *suppressed_exceptions: t.Type[Exception], **kwargs) -> asyncio.Task: - """Wrapper for `asyncio.create_task` which logs exceptions raised in the task.""" - task = asyncio.create_task(coro, **kwargs) +def create_task( + coro: t.Awaitable, + *suppressed_exceptions: t.Type[Exception], + event_loop: asyncio.AbstractEventLoop = None, + **kwargs +) -> asyncio.Task: + """ + Wrapper for creating asyncio `Task`s which logs exceptions raised in the task. + + If the loop kwarg is provided, the task is created from that event loop, otherwise the running loop is used. + """ + if event_loop is not None: + task = event_loop.create_task(coro, **kwargs) + else: + task = asyncio.create_task(coro, **kwargs) task.add_done_callback(partial(_log_task_exception, suppressed_exceptions=suppressed_exceptions)) return task -- cgit v1.2.3