我希望通过在python中调用函数来每5分钟更新一次变量值,而如果时间不是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
答案 0 :(得分:4)
如果您想进行异步函数调用,请查看:Timer Objects并使用它们(来自文档):
from threading import Timer
t = Timer(300.0, function_call)
t.start() # after 300 seconds, function_call will be called
否则更简单的解决方案(没有线程)就是检查与时间调用的区别(就像你试图做的那样):
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