简体   繁体   中英

Apscheduler cron to start on the half hour

I'm looking to have a cron job that runs based on the stock market open and close times (8:30-3 CST). I want it to run every 15 minutes, starting at 8:30.

What I currently have is

sched.add_job(scheduled_task,'cron',
   day_of_week='mon-fri', hour='8-15', 
   minute=enter code here'0-59/15', 
   timezone='America/Chicago')

This allows me to run 8am-3pm every 15 minutes which isn't exactly what I want. I have also tried the following:

sched.add_job(scheduled_task,'cron',
   day_of_week='mon-fri', hour='12-20',     
   minute='30/15', 
   timezone='America/Chicago')

This gets me closer but only runs on the 30 and 45 minutes.

I would say run your cron task every 15 minutes and just skip the execution of your code when the current time of day is before 8:30 (8 * 60 + 30)

import datetime
from apscheduler.scheduler import Scheduler

cron = Scheduler(daemon=True)
cron.start()

@cron.interval_schedule(minutes=15)
def job_function():
    now = datetime.datetime.now()
    if (now.hour * 60 + now.minute) > 8 * 60 + 30:
        return

    # code to execute

The solution is to use OrTrigger:

from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.combining import OrTrigger

cron1 = CronTrigger(day_of_week='mon-fri', hour='8', minute='30,45', timezone='America/Chicago')
cron2 = CronTrigger(day_of_week='mon-fri', hour='9-15', minute='*/15', timezone='America/Chicago')
trigger = OrTrigger([cron1, cron2])
sched.add_job(scheduled_task, trigger)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM