Python 计划每周五运行一项任务,但如果任务完成并在周五重新启动计算机,则避免运行两次;如果周五计算机关闭,则第二天再运行

Python 计划每周五运行一项任务,但如果任务完成并在周五重新启动计算机,则避免运行两次;如果周五计算机关闭,则第二天再运行,python,windows,scheduled-tasks,schedule,taskscheduler,Python,Windows,Scheduled Tasks,Schedule,Taskscheduler,我尝试使用各种方法使用Python安排特定任务: 使用time.sleep3600滚动我自己的日程安排,并每小时检查一次,见下文 像这样尝试图书馆 但要做到这一点似乎并不容易:我希望每周五运行一次任务,并满足以下两个条件: 如果完成了,我在周五重新启动计算机或重新启动Python脚本,我不希望任务在同一天再次运行 如果计算机在星期五关机,而我在星期六启动它,任务应该会运行,因为到那时,它本周还没有运行。 如何使用Python以良好的方式实现这一点 注意:我希望避免使用Windows任务调度器或其

我尝试使用各种方法使用Python安排特定任务:

使用time.sleep3600滚动我自己的日程安排,并每小时检查一次,见下文 像这样尝试图书馆 但要做到这一点似乎并不容易:我希望每周五运行一次任务,并满足以下两个条件:

如果完成了,我在周五重新启动计算机或重新启动Python脚本,我不希望任务在同一天再次运行 如果计算机在星期五关机,而我在星期六启动它,任务应该会运行,因为到那时,它本周还没有运行。 如何使用Python以良好的方式实现这一点

注意:我希望避免使用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可以重新表述为计算机在星期五关闭,因此任务应该在下次计算机打开时运行,那么您需要实现的只是:

- 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.
请注意,由于任务可能在本月最后一天的星期五运行,因此需要存储整个日期,而不仅仅是本月的某一天

要计算下周五的日期,请参阅当前评分最高的答案


向我们展示你迄今为止所做的尝试@美元。这里是^I编辑的。关于第二个要求:如果计算机在星期六也关闭,任务是在下次计算机打开时运行,还是应该等到下一个星期五,因为星期五和星期六是唯一允许的日期?@SiggiSv它应该在下次计算机打开时运行。谢谢你看这个问题!
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)