How to schedule a function to run every hour on Flask?

RomaValcer picture RomaValcer · Jan 19, 2014 · Viewed 118.1k times · Source

I have a Flask web hosting with no access to cron command.

How can I execute some Python function every hour?

Answer

tuomastik picture tuomastik · Jul 21, 2016

You can use BackgroundScheduler() from APScheduler package (v3.5.3):

import time
import atexit

from apscheduler.schedulers.background import BackgroundScheduler


def print_date_time():
    print(time.strftime("%A, %d. %B %Y %I:%M:%S %p"))


scheduler = BackgroundScheduler()
scheduler.add_job(func=print_date_time, trigger="interval", seconds=3)
scheduler.start()

# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())

Note that two of these schedulers will be launched when Flask is in debug mode. For more information, check out this question.