Search code examples
pythonapscheduler

How to set hour range and minute interval using APScheduler


I'm trying to create a process that can run jobs on a cron schedule of 0/5 8-17 * * 1-5 and here is my test code:

import argparse
from apscheduler.schedulers.background import BackgroundScheduler
import datetime
import time

cmdline_parser = argparse.ArgumentParser(description='Testing')
cmdline_parser.add_argument('--interval', type=int, default=5)

def task():
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
    print(f'{now}')

if __name__=='__main__':
    args = cmdline_parser.parse_args()
    sched = BackgroundScheduler(timezone='EST')
    sched.start()
    minutes_interval = f'0/{args.interval}'

    sched.add_job(task, trigger='cron', day_of_week='mon-fri', hour='8-17', minute=minutes_interval)

    while True:
        time.sleep(30)

But it is not stopping after 5pm. Please help if I'm using the cron arguments incorrectly.


Solution

  • cron hours index from 0 so use hour='7-16' instead of hour='8-17'

    sched.add_job(task, trigger='cron', day_of_week='mon-fri', hour='7-16', minute=minutes_interval)