Football52
Football52

Reputation: 151

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.

Upvotes: 0

Views: 6011

Answers (2)

Alex Grönholm
Alex Grönholm

Reputation: 5901

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)

Upvotes: 5

Jop Knoppers
Jop Knoppers

Reputation: 714

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

Upvotes: 1

Related Questions