运行我的程序一分钟然后暂停一分钟的最简单方法是什么



我这里有一些代码,每分钟打印一行,但我想更改它,以便它连续打印一分钟的消息,然后无限期暂停一分钟。我如何实现这一点?

import time
while True:
print("This prints once a minute.")
time.sleep(60) # Delay for 1 minute (60 seconds).

要连续打印消息一分钟,然后等待一分钟,然后无限期重复,您可以使用以下内容:

import time
while True:
s = time.time()
while time.time() < s + 60:
print("Message")
time.sleep(60)

如果要每秒打印一次消息,持续一分钟。您可以执行以下操作:

import time
original_time = time.time()
while time.time() < original_time + 60:
print("This prints every second for one minute")
time.sleep(1)

这就是你要找的吗?

您可以跟踪何时开始您的分钟,然后等待 60 秒。每 60 秒切换一次is_printing状态。

import time
is_printing = False
while True:
is_printing = not is_printing
start_time = time.time()
while time.time() - start_time < 60:
if is_printing:
print("Printing this for a minute.")

相关内容

最新更新