且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

即使使用asyncio和aiohttp,方法也会等待请求响应

更新时间:2023-01-13 09:50:59

如果我理解的很正确,您想在后台启动 getLastItemFromGivenInterval ,并且每60秒执行一次,无论完成多长时间。您可以将 await 替换为 create_task ,然后再也不等待生成的任务:

If I understand you correctly, you want to start getLastItemFromGivenInterval in the background, and do so every 60 seconds regardless of how long it takes to complete. You can replace await with create_task, and then never awaiting the resulting task:

loop = asyncio.get_event_loop()
while True:
    # spawn the task in the background, and proceed
    loop.create_task(bc.getLastItemFromGivenInterval(session))
    # wait 60 seconds, allowing the above task (and other
    # tasks managed by the event loop) to run
    await asyncio.sleep(60)

您可能还需要确保需要很长时间才能完成或无限期挂起的任务(例如,由于到网络故障)不要累积:

You might want to also ensure that tasks that take a long time to complete or that hang indefinitely (e.g. due to a network failure) don't accumulate:

loop = asyncio.get_event_loop()
while True:
    # asyncio.wait_for will cancel the task if it takes longer
    # than the specified duration
    loop.create_task(asyncio.wait_for(
        bc.getLastItemFromGivenInterval(session), 500))
    await asyncio.sleep(60)