让 Python 保持循环语句运行,并每 3 秒检查一次条件



我想保持循环条件语句运行,但并不总是检查条件。

例如,如果条件为 true,则在接下来的 3 秒内,循环的条件语句将运行,然后在第 3 秒后检查条件,然后重复此过程。

我不想等待或睡觉三秒钟,我希望我的循环工作三秒钟。然后检查它是否应该继续另外三个,如@RemcoGerlich

while if_active() == True:    #check the condition every 3 seconds` 
try:               # it will keep running in 3 seconds if if_active() is true  
with open(masterpath, 'r') as f:
s = f.read()
exec(s)

这是一种有趣且异步的方式。只是为了好玩,有一个演示来activate

import signal, os
import time
def handler(signum, frame):
for i in range(3):
print("foo bar")
time.sleep(0.1)
signal.alarm(3)
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(3)
while True:
try:
active = not active
if not active:
signal.alarm(0)
time.sleep(60)
except KeyboardInterrupt as interrupt:
# demonstrating activate, with ctrl+c
signal.alarm(3)

您可以跟踪上次执行检查的时间,并且仅在三秒钟后重新执行检查。

from datetime import datetime, timedelta
INTERVAL = timedelta(minutes=3)
last_checked = datetime.now() - INTERVAL
while True:
now = datetime.now()
if last_checked <= (now - INTERVAL):
if not if_active():
break
last_checked = now
# do your thing here
pass

这可能需要一些重构,但这个想法应该有效。

您可以使用 sleep 等命令来避免连续运行。您可以在此线程中看到更解释的答案:如何在 Python 中制造时间延迟?

最新更新