aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Numerlor <[email protected]>2021-06-12 16:07:24 +0200
committerGravatar Numerlor <[email protected]>2021-06-12 16:07:24 +0200
commit0b726398d2135ab414374412fa85f791569e3640 (patch)
tree76edf18b3d2f56bc4326dafdceff7db1d87112dc
parentMerge pull request #1636 from ichard26/reminder-for-psf-black (diff)
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.
-rw-r--r--bot/utils/scheduling.py18
1 files 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