在做其他事情的同时每 n 分钟定期执行一次函数

Periodically execute function every n minutes while doing other stuffs

我想基本上每 5 分钟更新一次变量值,方法是在 python 中调用一个函数,同时如果时间不是 5 分钟则执行其他任务。我试图使用 strftime 来计时但迷路了。不确定我犯了什么错误。非常感谢任何帮助。

    variable = 0
    start_time = strftime("%M")
    While True:
        {do something here}
        current_time = strftime("%M")
        diff = int(start_time) - int(current_time)
        if diff is 5 minutes:
            function_call() #updates the variable
        else:
            Use the old variable value
  1. 如果你想进行异步函数调用,请查看:Timer Objects 并按原样使用它们(来自文档):

    from threading import Timer
    t = Timer(300.0, function_call)
    t.start() # after 300 seconds, function_call will be called
    
  2. 否则更简单的解决方案(没有线程)只是检查时间调用的差异(正如您尝试做的那样):

    from time import time
    start_time = time()
    # do stuff
    if time() - start_time > 300: # 300 secs
        function_call()
    

因此使用第二个选项,您的代码可能如下所示:

from time import time
variable = 0
start_time = time()
While True:
    {do something here}
    current_time = time()
    diff = current_time - start_time
    if diff > 5*60:
        function_call() #updates the variable
        start_time = current_time
    else:
        Use the old variable value