【问题标题】:How can I submit another task_list after one task_list finished in asyncio module?在 asyncio 模块中完成一个 task_list 后,如何提交另一个 task_list?
【发布时间】:2019-03-25 04:48:03
【问题描述】:

我是 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 而不是 new 和 set。你有什么问题?
  • @MatrixTai,感谢您的回复,我只想一次运行1000个任务的一部分(例如100个),并在前100个任务完成后运行下100个任务..
  • @MatrixTai 这可行吗? loop.run_until_complete(asyncio.wait(task_list_100)) loop.run_until_complete(asyncio.wait(task_list_200)) loop.run_until_complete(asyncio.wait(task_list_300))...

标签: python python-asyncio


【解决方案1】:

要补充一点,

  1. get_event_loop 将尝试访问任何可用的事件循环,如果没有,它将调用 new_event_loopset_event_loop, [Doc]

  2. 当您不再执行任何单独的任务时,只需使用asyncio.gather。使用gather 也为您提供了一种停止整个任务组的方法,请参阅此SO answer

  3. 1234563 .如果不是,则改回[]括号。

整个工作示例将是:

# 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))

【讨论】:

  • 感谢您的耐心等待,您的话受益匪浅。 :)
猜你喜欢
  • 1970-01-01
  • 2021-07-31
  • 1970-01-01
  • 2012-03-28
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多