Skip to content
Advertisement

How can I run task every 10 minutes on the 5s, using BlockingScheduler?

I’m trying to run a task every 10 minutes, on the 5’s, for example, at 13:15, 13:25, ….

However, it is not working.

This is only running once an hour, at the beginning of the hour, from 12 to 4pm.

sched.add_job(run_batch, 'cron', day_of_week='mon-fri', hour='12-16', minute='5,15,25,35,45,55', timezone='America/Chicago')

Advertisement

Answer

The question title indicates that you are using the BlockingScheduler function of the Python library — Advanced Python Scheduler (APScheduler).

Based on your question, you want to run a cron job within a Python script Monday through Friday between 1200 and 1600. You want the job to run at 12:05, 12:15, 12:25, etc.

I have not fully tested the answer below, but I did run the test for 1 hour (starting at 8am today) and it fired correctly at 8:05, 8:15, 8:25, 8:35, 8:45, 8:55 and 9:05.

I used the start_date variable to start the scheduler at a precise date and time.

from datetime import datetime
from apscheduler.schedulers.background import BlockingScheduler

# BlockingScheduler: use when the scheduler is the only thing running in your process
scheduler = BlockingScheduler()

# Define the function that is to be executed
# at a scheduled time
def job_function():
    print(datetime.now().time().strftime('%H:%M'))

# Schedules the job_function to be executed Monday through Friday at between 12-16 at specific times.   
scheduler.add_job(job_function, 'cron', day_of_week='mon-fri', hour='12-16', minute='5,15,25,35,45,55', start_date='2021-03-23 12:00:00', timezone='America/Chicago')

# Start the scheduler
scheduler.start()

BTW You can replace these time intervals.

minute='5,15,25,35,45,55'

with this, which I tested.

minute='5-55/10'

Just a side question. Have you considered using UTC over Central Time?

from datetime import datetime
from apscheduler.schedulers.background import BlockingScheduler

# BlockingScheduler: use when the scheduler is the only thing running in your process
scheduler = BlockingScheduler()

# Define the function that is to be executed
# at a scheduled time
def job_function():
    print(datetime.utcnow().strftime('%H:%M'))

# Schedules the job_function to be executed Monday through Friday at between 12-16 at specific times.   
scheduler.add_job(job_function, 'cron', day_of_week='mon-fri', hour='17-21', minute='5-55/10', start_date='2021-03-23 12:00:00', timezone='UTC')

# Start the scheduler
scheduler.start()

Please let me know if you have any issues with this code and I will look into them for you.

Advertisement