RomaValcer RomaValcer - 2 months ago 61
Python Question

Flask - run function every hour

I have a Flask web hosting with no access to

cron
command.
How can I execute some Python function every hour?

Answer

To update Sean Vieira's answer: Since Scheduler() was removed in APScheduler v3.0, we can now (v3.2) use BackgroundScheduler():

import time
import atexit

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger

scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(
    func=print_date_time,
    trigger=IntervalTrigger(seconds=5),
    id='printing_job',
    name='Print date and time every five seconds',
    replace_existing=True)
# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())

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

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

Comments