python - 在特定时间戳上调用 python 函数

标签 python python-3.x api timestamp python-requests

我尝试每整分钟向 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/

相关文章:

python - MYSQL 数据插入查询在 Python 中不起作用

python - 如何在python中比较2个json

python - 属性错误: Map object has no attribute 'create_map'

python - 从 HTML 标签中包含的一系列字符串和不带标签的字符串中提取文本

带有 eCheck 的 PHP RestFul API

python - 相当于 DynamoDB 中不传递主键的选择查询?

python - 在 golang 中使用 mgo 排序为接口(interface)数组的字符串数组

python - 从具有更广泛命名空间的子目录前缀导入制作 setup.py?

api - 在 REST Api 调用中批量更新集合的最佳实践

android - SHA1 证书指纹