每天检查一次 - 如果今天不是 On 日,请继续睡觉直到明天。
或者
使用cron
(或 Windows 任务计划程序)将程序安排到所需的日期。
或者
import datetime
from time import sleep
SECONDS_PER_DAY = 3600 * 24
DAILY_START_TIME = datetime.time(8,15) # 8:15 am
def seconds(t):
return 3600*t.hour + 60*t.minute + t.second
def now():
t = datetime.datetime.now()
return t.weekday(), seconds(t)
def load_run_days():
# get data from registry
return [1,1,1,1,1,0,0]
def days_until_next_run(today, run_days=None):
if run_days is None:
run_days = load_run_days()
# rotate
run_days = run_days[today+1:] + run_days[:today+1]
# find next On day
for days,_on in enumerate(run_days, 1):
if _on:
return days
# no run day found?
raise ValueError("No 'On' days found")
def sleep_until_next_run():
today, elapsed = now()
days_to_wait = days_until_next_run(today)
sleep(-elapsed + days_to_wait*SECONDS_PER_DAY + seconds(DAILY_START_TIME))
def main():
while True:
try:
sleep_until_next_run()
except ValueError:
break
do_my_stuff()
if __name__=="__main__":
main()