Silver Silver - 3 months ago 40
Python Question

How can I schedule a script to run every 46 minutes, between 6:00 am and 23:40pm, daily with python?

I need a script to run every 46 minutes, between 6:00 am and 23:40pm, daily. Im currently using apscheduler, but I'm failing to set up the 24 runs per day on interval schedule, and programming each one of the run with a cron mode seems highly inefficient. Is there a simple way of telling python to "run this code every 46 minutes, 24 times a day, starting at 6am?"

Answer

Assuming you're not using asyncio, gevent, tornado, etc.

from apscheduler.schedulers.background import BackgroundScheduler

sched = BackgroundScheduler()
sched.start()
sched.add_job(function, 'cron', minute='46' hour='6-23')

See the docs for more details.

EDIT:

Misread the question. I'm assuming you wanted every 46 minutes, not AT the 46th minute every hour between 6 to 23. It would probably be better to have apscheduler event that stops an interval job at 23 and resumes it again at 6.

from apscheduler.schedulers.background import BackgroundScheduler
sched = BackgroundScheduler()

def disable_interval():
    sched.remove_job('INTERVAL_JOB')

def enable_interval():
    sched.add_job(run_function, 'interval', minutes=46, id='INTERVAL_JOB')

if __name__ == '__main__':
    sched.start()
    sched.add_job(enable_interval, 'cron', minute='0' hour='6')
    sched.add_job(disable_interval, 'cron', minute='40' hour='23')
Comments