【问题标题】:Whats the simplest way to run my program for one minute then pause it for one minute运行我的程序一分钟然后暂停一分钟的最简单方法是什么
【发布时间】:2020-05-09 01:39:27
【问题描述】:

我在这里有一些代码每分钟打印一次,但我想更改它,以便它直接打印一分钟的消息,然后无限期地暂停一分钟。我如何做到这一点?

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

【问题讨论】:

  • “连续打印一分钟消息”是指每秒打印一次吗?
  • 使用 cron 或你的操作系统调度器
  • 你做过研究吗?我相信这样的问题已经被问过很多次了。

标签: python python-3.x time while-loop


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您想在一分钟内每秒打印一次消息。您可以执行以下操作:

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

    这就是你要找的吗?

    【讨论】:

      【解决方案3】:

      您可以跟踪开始分钟的时间,然后等待 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.")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-29
        • 1970-01-01
        相关资源
        最近更新 更多