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

Python - Run Job every first Monday of month

背景: 我需要 运行 每个月的第一个和第三个星期一为服务器自动执行任务。 这应该通过 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()

是在年、月的第一个星期一还是每个星期一执行?

目前看来,此功能未在 schedule 包中实现:

schedule.every(3).monday.do(test)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/schedule/__init__.py", line 302, in monday
    raise IntervalError('Use mondays instead of monday')
schedule.IntervalError: Use mondays instead of monday
>>> schedule.every(3).mondays.do(test)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'Job' object has no attribute 'mondays'

我建议使用 while True 循环,并手动检查当天是否是该月的第一个星期一:

from datetime import datetime, date
import calendar

def find_first_monday(now):
    month_range = calendar.monthrange(now.year, now.month)
    date_corrected = date(now.year, now.month, 1)
    delta = (calendar.MONDAY - month_range[0]) % 7
    if not delta:
        return True
    return False

while True:
     now = datetime.now()
     if first_monday_of_the_month(now):
          TestFunction()
          time.sleep(24*3600)

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

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())

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