Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: prevent undone task be killed by gc #48

Merged
merged 1 commit into from
Jun 11, 2022
Merged
Changes from all commits
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
9 changes: 7 additions & 2 deletions src/graia/broadcast/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import sys
import traceback
from contextlib import asynccontextmanager
from typing import Callable, Dict, Iterable, List, Optional, Type, Union
from typing import Callable, Dict, Iterable, List, Optional, Set, Type, Union

from graia.broadcast.builtin.derive import DeriveDispatcher
from graia.broadcast.entities.dispatcher import BaseDispatcher
Expand Down Expand Up @@ -53,6 +53,8 @@ class Broadcast:
prelude_dispatchers: List["T_Dispatcher"]
finale_dispatchers: List["T_Dispatcher"]

_background_tasks: Set[asyncio.Task] = set()

def __init__(
self,
*,
Expand Down Expand Up @@ -257,7 +259,7 @@ async def param_compile(
dii.ctx.reset(dii_token)

def postEvent(self, event: Dispatchable, upper_event: Optional[Dispatchable] = None):
return self.loop.create_task(
task = self.loop.create_task(
self.layered_scheduler(
listener_generator=self.default_listener_generator(event.__class__),
event=event,
Expand All @@ -268,6 +270,9 @@ def postEvent(self, event: Dispatchable, upper_event: Optional[Dispatchable] = N
else [],
)
)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
return task

@staticmethod
def event_class_generator(target=Dispatchable):
Expand Down