我是 asyncio 模块的新手,请原谅我的糟糕尝试:
在我的代码中,我尝试首先提交 100 个任务,然后在前 100 个任务完成后提交接下来的 100 个任务,然后再提交接下来的 100 个任务。
我应该怎么做才能让它发挥作用?
# len(ad_accounts) = 1000 for example
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
task_list = [
asyncio.ensure_future(_handle_account(account)) for ad_account in ad_accounts[:100]
]
#just submit 100 tasks here once
new_loop.run_until_complete(asyncio.wait(task_list))
# then can I continuely submit next 100 tasks?
最佳答案
有几点需要补充
get_event_loop
将尝试访问任何可用的事件循环,如果没有,它将使用set_event_loop
调用new_event_loop
, [Doc] .当您不需要对单个任务执行任何进一步操作时,只需使用
asyncio.gather
即可。使用gather
还为您提供了一种停止整个任务组的方法,请参阅此 SO answer 。您可能会注意到,在下面的内容中,使用了
()
生成器而不是[]
列表理解,因为您不需要实际保存列表在内存中,并且在迭代之前您不需要它。如果不是这种情况,请改回[]
括号。
整个工作示例将是:
# len(ad_accounts) = 1000 for example
chunk_size = 100
batched_tasks = (ad_accounts[i:i + chunk_size] for i in range(0, len(ad_accounts), chunk_size))
_loop = asyncio.get_event_loop()
for task_group in batched_tasks:
task_list = [
asyncio.ensure_future(_handle_account(account)) for ad_account in task_group
]
#just submit 100 tasks here once
_loop.run_until_complete(asyncio.gather(*task_list))
# Or _loop.run_until_complete(asyncio.wait(task_list))
关于python - 在 asyncio 模块中完成一个任务列表后,如何提交另一个任务列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55331403/