我尝试使用各种方法来安排使用Python的特定任务:
- 滚动我自己的调度(使用
time.sleep(3600)
并每小时检查),请参见下文 - 尝试诸如计划的库
但是,拥有这个任务似乎并不容易:我希望在每个星期五在这两个条件下运行一次:
- 如果完成了,我在星期五重新启动计算机(或重新启动Python脚本),我不希望任务在同一天第二次运行
- 如果计算机在星期五关闭,我在星期六开始,该任务应运行(因为那时它已经运行了,本周已经运行了)。
如何用Python以一种很好的方式做到这一点?
nb:我想避免使用Windows任务调度程序或周围的包装器
nb2:安排任务的python脚本会在Windows启动上自动启动。
这是我尝试过的,但是它不是很优雅,并且不符合要求2.此外,我自己的日程安排可能不是最佳的,我正在寻找"高级"的东西。
try:
with open('last.run', 'r') as f:
lastrun = int(f.read())
except:
lastrun = -1
while True:
t = datetime.datetime.now()
if t.weekday() == 4 and t.day != lastrun:
result = doit() # do the task
if result:
with open('last.run', 'w') as f:
f.write(str(t.day))
print('sleeping...')
time.sleep(3600)
由于需求2可以作为 "if the computer is off on a Friday, the task should run the next time the computer is on"
重新塑造,因此您需要实现的只是:
- Figure out the date when the task should run next time.
- Inside an endless loop:
- if today is equal or greater than when the task should run next time:
- run task and then (if successful) update when task should run to next Friday after today.
请注意,由于可能会发生该任务是在一个月的最后一天进行的,因此需要存储整个日期,而不仅仅是每月的一天。
要计算下周五的日期,请参见当前如何估计估计的纽约 - 周五
的最高额定答案try:
with open('next.run', 'r') as f:
nextrun = datetime.date.fromordinal(int(f.read()))
except:
# Calculate date of next Friday (including today if today is indeed a Friday)
today = datetime.date.today()
nextrun = today + datetime.timedelta( (4 - today.weekday()) % 7 )
while True:
today = datetime.date.today()
if today >= nextrun:
result = doit() # do the task
if result:
# Calculate date of next Friday after today (the day after next Thursday)
daysuntilnext = (3 - today.weekday()) % 7) + 1
nextrun = today + datetime.timedelta(daysuntilnext)
with open('next.run', 'w') as f:
f.write(str(nextrun.toordinal()))
# Optional: sleep for (daysuntilnext - 1) days
print('sleeping...')
time.sleep(3600)
只需保存在日期时间对象中运行脚本的日期 - 带有泡菜或txtfile,或在数据库中,在deamon线程中创建一个函数,如果您想对其进行parralalle(或/和使用芹菜或" Python |计划库"在周五运行任务。当时是星期五,您的功能会在日期和日期之间检查差异(delta in Date.time)您节省了早期,如果差异> 6您运行脚本并再次保存日期。