我想每隔几秒钟在Python中运行一个函数。函数执行需要一些时间,我也希望将其包括在等待时间中。
我不想这样做,因为它不是每2秒严格执行一次,并且会破坏周期性(my_function也需要时间才能执行。)
while True:
time.sleep(2)
my_function()
我也不想这样做,因为它在Thread-2的while循环中占用了过多的CPU。
# Thread-1
While True:
time.sleep(2)
event.set()
# Thread-2
While True:
if event.is_set():
my_function()
else:
pass
有人可以帮助我吗?