我尝试每整分钟向 API 发送一次查询,因为 API 每分钟都会更新其数据,而我希望立即更新数据。重要的是时间要非常精确,我希望所有的事情都能持续地运行到最后。
这就是我想要做的:
import time, sched
time = 1549667056000 # starting timestamp
def get_data(): # function to get some data from the API via requests
#gets the Data
while true:
s.scheduler(time)
s.run(get_data()) # gets the data on the specified time(stamp)
time = time + 60000 # adds 1 minute to the timestamp
我应该这样做吗,还是有一种更智能的方法可以每整分钟从 REST Api 获取数据?
最佳答案
您可以使用asyncio.sleep
对于 Python <3.7
import asyncio
def get_data():
print("Getting data")
async def main():
while true:
get_data()
await asyncio.wait(MINUTE)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
对于 Python 3.7+
import asyncio
def get_data():
print("Getting data")
async def main():
while true:
get_data()
await asyncio.wait(60)
#This is the only thing that changes
asyncio.run(main)
编辑
根据您的评论,如果您真的担心确保每 60 秒调用一次。
您可以实现一种方法,在调用 get_data
之前获取时间,然后从 60 中减去该时间,只需确保 get_data
等待时间是否超过 60 秒0 秒或根本没有。
像这样的 main()
应该可以工作:
#make sure to:
import time
async def main():
while true:
t = time.time()
get_data()
time_diff = int(time.time() - t)
await asyncio.wait(max(60 - time_diff, 0))
关于python - 在特定时间戳上调用 python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54602346/