Search code examples
pythonpython-2.7scheduling

Python script schedule to run on day 1 of each month at 2:00 am


I have a script that runs every 30 minutes but there is a section I just want to run on the first of the month at 2:00 am. I am using schedule in Python and I can't figure out how to set it for day 1 of the month.

month doesn't seem to be in the defined parameters of schedule to do something like schedule.every().month.at("02:00").do(job2)

Any suggestions? I am using python 2.7

Simplified code:

from safe_schedule import SafeScheduler
import time

def job():
    print "I'm working...",
    return

def scheduler():
    # Schedule every30min routines
    print 'Starting Scheduler'
    scheduler = SafeScheduler()
    scheduler.every(30).minutes.do(job)
    #scheduler.every().month.at("02:00").do(job2)

    while True:
        scheduler.run_pending()
        time.sleep(1)


if __name__ == '__main__':
     scheduler()

Solution

  • The main contributor of the library discourages this sort of thing, see https://github.com/dbader/schedule/issues/73#issuecomment-167758653.

    Yet, if one insists, one can schedule a daily job but run it only if it's the 1st of the month.

    from datetime import date
    
    from safe_schedule import SafeScheduler
    
    
    def job2():
        if date.today().day != 1:
            return
    
        # actual job body
    
    
    scheduler = SafeScheduler()
    scheduler.every().day.at("02:00").do(job2)
    

    Another alternative is described in one of the issue comments https://github.com/dbader/schedule/issues/73#issuecomment-356769023.