python 收集后动态添加新任务(*tasks)

yyyllmsg  于 2022-12-10  发布在  Python
关注(0)|答案(1)|浏览(156)

例如以下代码:

async def f1(num):
    while True:
        print(num)
        await asyncio.sleep(2)

class ExampleClass:
  def __init__():
     self.tasks = []

  async def main():
    for i in range(10):
        tasks.append(asyncio.create_task(f1(i)))
    await asyncio.gather(*tasks)

  def add_new_task(task):
      self.tasks.append(task)

然后我在外面的某个地方呼唤

ExampleClass.add_new_task(task)

我需要的是添加新任务并与现有任务异步执行。
也许我应该使用任何其他的结构来实现我想要的东西?重要的是我的任务可能需要永远执行(永远轮询)

vjrehmav

vjrehmav1#

asyncio.gather函数对于这样的任务并不方便,但是你可以看看Python3.11发布的asyncio.TaskGroup,它允许更容易地动态添加新任务。

import asyncio
from concurrent.futures import wait, FIRST_COMPLETED

async def main():
    async with asyncio.TaskGroup() as group:
        # Create some tasks
        tasks = [
            group.create_task(asyncio.sleep(1.0))
            for _ in range(10)
        ]
        
        # Wait for some tasks to finish
        done, tasks = await wait(tasks, return_when=FIRST_COMPLETED)

        # Add more tasks (/!\ `tasks` is now a set)
        tasks.add(group.create_task(asyncio.sleep(2.0)))
       
       # Wait the rest to complete 
        await asyncio.gather(*tasks)

if __name__ == "__main__":
    asyncio.run(main())

相关问题