Python 休眠到特定时间

Mat*_*att 0 python sleep scheduled-tasks thread-safety

我有一个 Python 脚本,我也想在凌晨 3 点运行它。想简单地把这样的东西放在它的顶部。

while not 3am:
    sleep(10)
Run Code Online (Sandbox Code Playgroud)

这样它会持续睡眠 10 秒钟,直到凌晨 3 点。在凌晨 3 点,它执行下面的其余代码,然后退出脚本。有没有一种简单的方法可以做到这一点?

Ray*_*ger 6

具有睡眠等待循环的解决方案:

import datetime
import time

target_time = datetime.datetime(2017, 3, 7, 3)  # 3 am on 3 July 2017
while datetime.datetime.now() < target_time:
    time.sleep(10)
print('It is 3am, now running the rest of the code')
Run Code Online (Sandbox Code Playgroud)

如果您不想睡觉,而是想做其他工作,请考虑使用threading.Timersched模块

  • 这几乎正​​是我想要的,但我认为存在小错误。不应该是:datetime.datetime(2017, 7, 3, 3) 明天凌晨3点去吗? (2认同)