【问题标题】:Better way to execute code at a specific time?在特定时间执行代码的更好方法?
【发布时间】:2022-01-16 12:31:15
【问题描述】:

我需要在准确的时间执行代码,例如10:00:00.000

while True:
    now = datetime.utcnow()

    if now.hour == 10 and now.minute == 0 and now.second == 0:
        #execute code here
    time.sleep(1)

到目前为止,它似乎有效,但如果我在启动前一小时启动代码,我会觉得执行有延迟?

这是实现我想要的最好的吗?

【问题讨论】:

  • 您可以使用计划库。为此,请参阅this post

标签: python python-3.x time


【解决方案1】:

使用datetimethreading.Timer

from datetime import datetime, time
from threading import Timer


def do_the_thing():
    print("execute code here")


Timer(
    (datetime.combine(
        datetime.today(), time(10, 0, 0)
    ) - datetime.now()).total_seconds(),
    do_the_thing
).start()

由于Timer 在后台线程中运行,您的脚本可以立即继续执行其他操作,而do_the_thing 将在计时器到时立即被调用。

【讨论】:

    【解决方案2】:

    只需在所需的总时间内睡眠:

    target_date = datetime(day=12, month=12, year=2021, hour=10)
    time.sleep((target_date - datetime.now()).total_seconds())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      相关资源
      最近更新 更多