python-3.xschedule

Python scheduling a job starting every weekday and running every hour


I currently have a sample code defined as:

import schedule
import time

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

schedule.every().day.at("01:00").do(job,'It is 01:00')

while True:
    schedule.run_pending()
    time.sleep(60) # wait one minute

I am looking to however run the code every hour on weekdays from 9AM to 4PM. i.e. every day Monday through Friday I want to run the code at 9AM, 10AM, ..., 3PM, 4PM.

Reading the documentation for schedule it seems that I can run the code individually Monday through Friday but not only weekday between two specified times.

Also, shouldn't the following time.sleep(60) make the code run perpetually?


Solution

  • You can use library APScheduler. For example:

    from apscheduler.schedulers.blocking import BlockingScheduler
    
    def job_function():
        print("Hello World")
    
    sched = BlockingScheduler()
    
    # Runs from Monday to Friday at 5:30 (am) until
    sched.add_job(job_function, 'cron', day_of_week='mon-fri', hour=5, minute=30)
    sched.start()