【发布时间】:2021-04-16 21:32:34
【问题描述】:
我一直在尝试为我的 discord.py 机器人添加一个循环后台任务系统,但是一旦一个任务开始运行,它就会阻止其他任务。我试过到处寻找答案,但要么他们使用的是 discord.py 的重写版本,要么他们只有一项任务。
我正在尝试使任务并行运行,以便所有任务都可以同时运行。
这是我的代码:
# hiding imports
class BackgroundTasksCollection:
def __init__(self, client: discord.Client):
self.client = client
async def start_tasks(self):
tasks = []
for name in dir(self):
if name.startswith("task_"):
print(name)
tasks.append(getattr(self, name))
[await self.client.loop.create_task(task()) for task in tasks]
# tasks
async def task_1(self): # only this will run because the tasks are started in alphabetical order
await self.client.wait_until_ready()
while not self.client.is_closed():
await asyncio.sleep(60 * 60)
# ...
async def task_2(self):
await self.client.wait_until_ready()
while not self.client.is_closed():
await asyncio.sleep(1)
# ...
async def task_3(self):
await self.client.wait_until_ready()
while not self.client.is_closed():
await asyncio.sleep(30)
# ...
class MyClient(discord.Client):
def __init__(self, **options):
super().__init__(**options)
self.tasks = BackgroundTasksCollection(self)
async def on_ready(self):
# ...
await self.tasks.start_tasks()
# handle message, errors, etc.
【问题讨论】:
标签: python discord.py python-asyncio background-task