Python-每个月的第一个星期一运行作业

Nik*_*sla 5 python cron schedule

背景:我需要在服务器的每个月的第一个和第三个星期一运行自动任务。这应该通过python而不是crontab来实现。

我找到了python模块“ schedule”,但未详细说明其文档。 https://pypi.org/project/schedule/

https://schedule.readthedocs.io/en/stable/

有人知道怎么做这个吗?

import schedule

def TestFunction():
    pass

schedule.every(1).monday.do(TestFunction)
schedule.every(3).monday.do(TestFunction)
schedule.run_pending()
Run Code Online (Sandbox Code Playgroud)

这将在每年,每月或每个星期一的第一个星期一执行吗?

Ada*_*old 3

这是一个可能的解决方案:

import datetime

def something():
    day_of_month = datetime.now().day
    if (day_of_month > 7 and day_of_month < 15) or day_of_month > 21:
        return # not first / third monday of month
    # your code

schedule.every().monday.do(something())
Run Code Online (Sandbox Code Playgroud)

调度程序将在每个星期一运行,但return如果这不是该月的第一个/第三个星期一。