Search code examples
pythonscheduled-tasks

Executing an scheduled task if the script is run too late and after the scheduled time, using the `schedule` library


Imagine I want to run this function:

def main():
    pass

at these scheduled times (not every random 3 hours):

import schedule
schedule.every().day.at("00:00").do(main)
schedule.every().day.at("03:00").do(main)
schedule.every().day.at("06:00").do(main)
schedule.every().day.at("09:00").do(main)
schedule.every().day.at("12:00").do(main)
schedule.every().day.at("15:00").do(main)
schedule.every().day.at("18:00").do(main)
schedule.every().day.at("21:00").do(main)

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

How can I make this run main() immediately when the script is run at some time between the scheduled start times, say at 19:42. This works fine but if the something happens like the power goes out and I'm not there to restart the script and miss a scheduled run, I'd like it to execute the function as soon as the script is run again even if it's not at one of the scheduled times. This is Windows machine if it matters.


Solution

  • I think you need just to add main() call before the while loop, with check of current time

    import datetime
    # other schedules
    ...
    schedule.every().day.at("21:00").do(main)
    
    
    now = datetime.datetime.now()
    if 0 <= now.hour <= 20:
        main()  # <-- this will be called once, at script start if current time is between 00:00 and 21:00
    
    while True:
        schedule.run_pending()
        time.sleep(1)