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

编程入门 行业动态 更新时间:2024-10-28 08:26:11
本文介绍了即使使用asyncio和aiohttp,方法也会等待请求响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下问题,我想执行getlastItemFromGivenInterval方法,让它简短地通过而不等待请求响应,并为asyncio.sleep(60)提供上下文以在60秒内再次执行整个过程时间范围。我得到的是在getLastItemFromGivenInterval()中等待请求结束。

Hi I have the following issue, I want to execute getlastItemFromGivenInterval method, let it briefly to go through without waiting for request reponses, and give a context to asyncio.sleep(60) to execute the whole procedure once more in 60 seconds time frames. What I get is waiting in getLastItemFromGivenInterval() for request end.

import aiohttp import asyncio loop = asyncio.get_event_loop() task = loop.create_task(main()) loop.run_forever() async def main(): async with aiohttp.ClientSession() as session: while True: await bc.getLastItemFromGivenInterval(session) await asyncio.sleep(60) async def getLastItemFromGivenInterval(session): async with session.get(BinanceClient.base_endpoint + "/api/v1/time") as currentServerTime: currentServerTime = await currentServerTime.json() currentServerTime = currentServerTime['serverTime'] async with session.get(url) as res: response = await res.json() array = [] print(response) return response

getLastItemFromGivenInterval放在单独的类中。 请给我一个提示,如何在getLastItem ...()方法中达到不等待的效果。

getLastItemFromGivenInterval is placed in the separate class. Please give me a hint how to achieve not waiting effect in getLastItem...() method.

推荐答案

如果我理解的很正确,您想在后台启动 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)

更多推荐

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

本文发布于:2023-11-23 09:41:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620978.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:也会   方法   asyncio   aiohttp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!