【问题标题】:How can I run my code at a specific time? [duplicate]如何在特定时间运行我的代码? [复制]
【发布时间】:2021-10-12 11:52:49
【问题描述】:

我正在用 python 开发一个软件。我希望我的代码在特定时间运行。它将每 5 分钟运行一次,不会中断。但我希望它在特定的时间和分钟内准确地工作。比如20:00、20:05、20:10...

我使用了 time.sleep(300) 但是如果例如在我的程序运行后 5 秒过去了,它在每次运行中开始延迟 5 秒,例如它在 12 次运行后开始延迟 1 分钟运行。例如,它应该在 20:05 开始工作,但它从 20:06 开始。

我怎样才能提供这个?

【问题讨论】:

  • 假设程序除了在运行之间休眠之外什么都不做,最简单的方法可能是使用 CRON 作业在指定时间运行程序,而不是休眠程序。
  • cron 是您应该考虑的正确方式。

标签: python datetime time


【解决方案1】:

你可以使用调度模块

import schedule
import time
from datetime import datetime

now = datetime.now()

def omghi():
    print("omg hi there xD")


schedule.every(5).minutes.do(omghi)


while True:
    schedule.run_pending()
    time.sleep(1)

【讨论】:

  • 提醒一下,要使用 schedule 你首先需要使用 pip 安装它
【解决方案2】:

对于这种情况有一个有用的模型。 它是一个外部模型,你必须使用 pip 下载它,它被称为 schedule https://pypi.org/project/schedule/ - 在这里你可以看到所有的细节。

【讨论】:

    【解决方案3】:

    我相信使用定时线程最能满足您的需求。 This excellent answer 使用库中的 threading.Timer threading 如下:

    import threading
    
    def printit():
      threading.Timer(5.0, printit).start()
      print "Hello, World!"
    
    printit()
    

    【讨论】:

      【解决方案4】:

      非常感谢您的回答。但这就是我的处理方式,我想和你分享:)

      import time
      from datetime import datetime
      
      while True:
          now = datetime.now()
      
          if (now.minute % 5) == 0 and now.second == 0:
              print("Fire!")
      
          time.sleep(1)
      

      【讨论】:

        猜你喜欢
        • 2012-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-18
        • 2021-05-28
        • 1970-01-01
        • 2022-01-24
        相关资源
        最近更新 更多