每 x 秒调用一次函数(Python) [英] Call function every x seconds (Python)

查看:38
本文介绍了每 x 秒调用一次函数(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每 10 秒调用一次函数(实际上,它是一个 Web API).但是该函数可能需要随机 t 秒才能返回.(假设 t 为 0.1 到 1.0 秒)

I want to call a function (actually, it is a web API) every 10 seconds. But the function may take random t second to return. (Assume t is 0.1 to 1.0 sec)

我们能想到的最简单的代码是

The simplest code we can think of is

while True:
    func()          # take t sec
    time.sleep(10)  # sleep 10 sec

但在这种情况下,func 每 (1+t) 秒被调用一次.有没有更好的方法来做到这一点?

but in this case, func is called every (1+t) seconds. Are there better ways to do it?

我们应该使用一些多线程或类似的东西吗?具体的代码示例将不胜感激.谢谢.

Should we use some multi threading or something like that? Concrete code example will be appreciated. Thank you.

推荐答案

只要记住下一次迭代应该发生的时间,大致是这样的(不是完全工作的代码,我相信你可以从这里弄清楚):

Just remember when the next iteration is supposed to happen, roughly like this (not fully working code, I'm sure you can figure it out from here):

import time
nexttime = time.time()
while True:
    func()          # take t sec
    nexttime += 10
    sleeptime = nexttime - time.time()
    if sleeptime > 0:
        time.sleep(sleeptime)

这篇关于每 x 秒调用一次函数(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆