【发布时间】:2021-10-16 14:31:51
【问题描述】:
我需要定期调用任务,但 (a) 等待时间几乎超过了周期。
在下面的代码中,如何运行do_something() 任务而不需要await 获得结果?
import asyncio
import time
from random import randint
period = 1 # Second
def get_epoch_ms():
return int(time.time() * 1000.0)
async def do_something(name):
print("Start :", name, get_epoch_ms())
try:
# Do something which may takes more than 1 secs.
slp = randint(1, 5)
print("Sleep :", name, get_epoch_ms(), slp)
await asyncio.sleep(slp)
except Exception as e:
print("Error :", e)
print("Finish :", name, get_epoch_ms())
async def main():
i = 0
while True:
i += 1
# Todo : this line should be change
await do_something('T' + str(i))
await asyncio.sleep(period)
asyncio.get_event_loop().run_until_complete(main())
【问题讨论】:
-
等待结果的时间不可能比产生结果的时间更短。你能更详细地描述一下这个问题吗?
-
是的,当然。我正在使用 API 调用从多个网站获取加密货币数据。我的目标是以恒定周期(最后周期的平均值)调用获取数据 API。让我们假设每分钟 60 个请求。有些网站懒得回答。例如,假设所有响应将在 10 秒后交付。真的我不在乎什么时候会收到响应(甚至在 60 秒后它可能会出现超时错误)。这等待 API 响应很烦人。我只想发送相同周期的请求。
标签: python python-3.x asynchronous async-await python-asyncio