每x秒调用一次函数(Python) [英] Call function every x seconds (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
,但在这种情况下,每(1 + t)秒调用一次 func
.有没有更好的方法来做到这一点?
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屋!