Ad

How To Schedule A Python Function To Run Every Hour At Specific Minute (ex 00, 10, 20) With Apscheduler

I try to schedule a function within my script to run at a specific minute every hour, i.e. if my script starts running at 11.46 my function to run at 11.50, 12.00, 12.10 etc and to do the same thing if it fails and restarts. I have seen that it is possible to do this with cron from command line but is there a way to do it while the script is running with a scheduler?

I have already created a scheduler which runs every 10 minutes after my script starts, but I want my function to run on specific minutes not just specific intervals.

from apscheduler.schedulers.background import BackgroundScheduler
import atexit

def demo_job:
    print("test")

try:
    sched = BackgroundScheduler(daemon=True)
    sched.add_job(demo_job, trigger='interval', minutes=10)
    sched.start()
    atexit.register(lambda: sched.shutdown(wait=False))
except:
    print("Unexpected error:")

If my script starts running at 11.47 the first scheduled call of my function is at 11.57, the next at 12.07, 12.17 etc... I want the first run to be at 12.00, the next at 12.10, 12.20 etc

Ad

Answer

You can try using the cron trigger.

sched.add_job(
    demo_job, 
    trigger='cron',
    minute='*/10',
    hour='*'
)

The expression */10 will fire the job at every tenth minute, starting from the minimum value. Crontab ref

Ad
source: stackoverflow.com
Ad