Search code examples
pythoncronschedule

Python - Run Job every first Monday of month


Background: I need to run automatic tasks every first and third monday of the month for a server. This should be realised via python not crontab.

I found the python module "schedule" but its documentation is not detailed. https://pypi.org/project/schedule/

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

Does anybody know how to do this?

import schedule

def TestFunction():
    pass

schedule.every(1).monday.do(TestFunction)
schedule.every(3).monday.do(TestFunction)
schedule.run_pending()

Will this be executed on the first monday of the year, month or every monday?


Solution

  • Here's a possible solution:

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

    The scheduler will run every monday, but we return if this is not the first / third monday of the month.