我如何从一个特定的纪元开始每四分钟运行一个函数?



我的main函数在while True:循环中调用了许多子程序。

我想添加另一个函数g(),它每四分钟只运行一次。功能g()只能在4分钟、8分钟、12分钟等时间运行

我知道我可以检查if epoch >= x是否经过了一段时间

但是我如何每四分钟只运行g()呢?

def main():
epoch = time.time()
count = 0 
while True:        
count = count + 1        
if a() == 1:
b()
c()
d()
if count % 20:
e()
else:
f()
e()
if epoch >= 240:
g()

编辑;我不能运行这个作为一个单独的线程作为重复建议的答案。

创建一个新变量来存储下次函数应该运行的时间:

import time
def main():
epoch = time.time()
count = 0
next_g = 0
while True:        
count = count + 1        
if a() == 1:
b()
c()
d()
if count % 20:
e()
else:
f()
e()
if (epoch := time.time()) >= next_g:
g()
next_g = epoch + 240

相关内容

最新更新