How to perform periodic task with Flask in Python How to perform periodic task with Flask in Python python python

How to perform periodic task with Flask in Python


For my Flask application, I contemplated using the cron approach described by Pashka in his answer, the schedule library, and APScheduler.

I found APScheduler to be simple and serving the periodic task run purpose, so went ahead with APScheduler.

Example code:

from flask import Flaskfrom apscheduler.schedulers.background import BackgroundSchedulerapp = Flask(__name__)def test_job():    print('I am working...')scheduler = BackgroundScheduler()job = scheduler.add_job(test_job, 'interval', minutes=1)scheduler.start()


You could use cron for simple tasks.

Create a flask view for your task.

# a separate view for periodic task@app.route('/task')def task():    board.read()    board.digital_outputs = board.digital_inputs

Then using cron, download from that url periodically

# cron task to run each minute0-59 * * * * run_task.sh

Where run_task.sh contents are

wget http://localhost/task

Cron is unable to run more frequently than once a minute. If you need higher frequency, (say, each 5 seconds = 12 times per minute), you must do it in tun_task.sh in the following way

# loop 12 times with a delayfor i in 1 2 3 4 5 6 7 8 9 10 11 12do    # download url in background for not to affect delay interval much    wget -b http://localhost/task    sleep 5sdone


No there is not tasks support in Flask, but you can use flask-celery or simply run your function in separate thread(greenlet).