gpt4 book ai didi

python - 安排Python程序在给定时间段内休眠

转载 作者:太空宇宙 更新时间:2023-11-04 05:52:39 24 4
gpt4 key购买 nike

while True:
now = datetime.datetime.now();
if now.hour >= 22 and now.hour < 3:
print "sleep"
sleep_at = datetime.datetime.combine(datetime.date.today(),datetime.time(3))
sleep_til = (sleep_at - now).seconds
print sleep_til
time.sleep(sleep_til)
print "wake"
else:
print "break"
break

这段代码应该让我的整个程序在晚上 10 点进入休眠状态并在凌晨 3 点醒来。我的问题是..这会起作用吗?我尝试运行它..但我无法更改我的系统/计算机时间..所以我无法检查。我发布这个问题的原因是因为我的编码使用 datetime.date.tday 和 datetime.datetime 调用当前日期..

再一次..我希望我的程序在晚上 10 点之前运行,并在晚上 10 点到凌晨 3 点之间休眠,并在凌晨 3 点之后重新运行。

有人可以检查这是否是正确的方法吗?

最佳答案

考虑(为了清晰起见,更加详细):

import time, datetime

# Create time bounds -- program should run between RUN_LB and RUN_UB
RUN_LB = datetime.time(hour=22) # 10pm
RUN_UB = datetime.time(hour=3) # 3am

# Helper function to determine whether we should be currently running
def should_run():
# Get the current time
ct = datetime.datetime.now().time()
# Compare current time to run bounds
lbok = RUN_LB <= ct
ubok = RUN_UB >= ct
# If the bounds wrap the 24-hour day, use a different check logic
if RUN_LB > RUN_UB:
return lbok or ubok
else:
return lbok and ubok


# Helper function to determine how far from now RUN_LB is
def get_wait_secs():
# Get the current datetime
cd = datetime.datetime.now()
# Create a datetime with *today's* RUN_LB
ld = datetime.datetime.combine(datetime.date.today(), RUN_LB)
# Create a timedelta for the time until *today's* RUN_LB
td = ld - cd
# Ignore td days (may be negative), return td.seconds (always positive)
return td.seconds


while True:
if should_run():
print("--do something--")
else:
wait_secs = get_wait_secs()
print("Sleeping for %d seconds..." % wait_secs)
time.sleep(wait_secs)

但我确实同意 sleep 并不是延迟程序开始的最佳方法。您可以查看 Windows 上的任务计划程序或 Linux 上的 cron

关于python - 安排Python程序在给定时间段内休眠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29086440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com