每x秒调用一次函数(Python)

每x秒调用一次函数(Python),python,api,loops,time,Python,Api,Loops,Time,我想每10秒调用一个函数(实际上,它是一个web API)。但函数可能需要随机t秒才能返回。(假设t为0.1至1.0秒) 我们能想到的最简单的代码是 while True: func() # take t sec time.sleep(10) # sleep 10 sec 但是在这种情况下,每隔(1+t)秒调用一次func。 有更好的方法吗 我们应该使用多线程或类似的东西吗?具体的代码示例将不胜感激。谢谢。您可以使用以下内容: import time sta

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

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

while True:
    func()          # take t sec
    time.sleep(10)  # sleep 10 sec
但是在这种情况下,每隔(1+t)秒调用一次
func
。 有更好的方法吗


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

您可以使用以下内容:

import time
start=time.perf_counter()
call_new_func()
while ((time.perf_counter()-start)<desired_time_wait):
    pass #busy-wait
导入时间
开始=时间。性能计数器()
调用新函数()

虽然((time.perf_counter()-start)只需记住下一次迭代应该在什么时候进行,大致如下所示(不是完全正常工作的代码,我相信您可以从这里了解它):

试试这个:

from multiprocessing import Pool
import time

pool = Pool(processes=1)              # Start a worker processes.
while true:
    result = pool.apply_async(func, [10], callback=finish) # Evaluate "func(10)" asynchronously calling callback when finished.
    time.sleep(10)

这将精确地每10秒调用一次函数。只要您确定返回所需时间不会超过10秒,您应该可以只使用一个辅助进程。来源于此处:

我发现了另一种使用
sched
模块的方法

import time
import sched

def daemon(local_handler, t):
    print('time {}'.format(t))
    # call func here
    # time.sleep(2)
    local_handler.enterabs(t + 10, 1, daemon, (local_handler, t+10))

handler = sched.scheduler(time.time, time.sleep)
t = time.time()
handler.enter(0, 1, daemon, (handler, t))
handler.run()
这种方法的一个优点是我们可以精确地控制函数的时间。例如,我们可以在时钟为0.31、10.31、20.31、30.31


这段代码取自。

当然,如果你想浪费电能并降低计算机速度!注意OP的代码占空比不到10%,因此这将浪费90%以上的资源。据我了解,这种循环(在C中)实际上是Python内部为
time.sleep()所做的
。不,Python使用
select()
或其他非繁忙等待方法。正如您在链接的
pysleep
的代码中所看到的。可能相关?您可以每10秒生成一个异步调用的子程序。这与处理所花的时间无关。为什么不使用
cron
?您可以使用
sched
python内置标准库中的(调度程序)模块。@YamanJain您能演示如何调度吗?谢谢。我认为这是最简单也是最好的方法。感谢您提供的好代码。这是我隐约想象的。我发现由于
池,间隔略长于10秒。apply_async
调用时间。
import time
import sched

def daemon(local_handler, t):
    print('time {}'.format(t))
    # call func here
    # time.sleep(2)
    local_handler.enterabs(t + 10, 1, daemon, (local_handler, t+10))

handler = sched.scheduler(time.time, time.sleep)
t = time.time()
handler.enter(0, 1, daemon, (handler, t))
handler.run()