0
0
FlaskHow-ToBeginner · 4 min read

How to Schedule Tasks in Flask: Simple Guide with Examples

To schedule tasks in Flask, use the APScheduler library which integrates easily with Flask apps. Define jobs with decorators or add them programmatically, then start the scheduler to run tasks at set intervals or times.
📐

Syntax

Use APScheduler with Flask by creating a scheduler instance, adding jobs, and starting it. Jobs can be scheduled using triggers like interval, date, or cron.

  • BackgroundScheduler(): Creates the scheduler that runs in the background.
  • add_job(func, trigger, **kwargs): Adds a task function with a trigger type and timing details.
  • start(): Starts the scheduler to run jobs.
python
from apscheduler.schedulers.background import BackgroundScheduler

scheduler = BackgroundScheduler()

def my_task():
    print('Task executed')

# Add a job to run every 10 seconds
scheduler.add_job(func=my_task, trigger='interval', seconds=10)

scheduler.start()
💻

Example

This example shows a Flask app that prints a message every 5 seconds using APScheduler's interval trigger.

python
from flask import Flask
from apscheduler.schedulers.background import BackgroundScheduler
import atexit

app = Flask(__name__)

scheduler = BackgroundScheduler()

def scheduled_task():
    print('Task is running every 5 seconds')

scheduler.add_job(func=scheduled_task, trigger='interval', seconds=5)
scheduler.start()

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

@app.route('/')
def home():
    return 'Flask Scheduler Running'

if __name__ == '__main__':
    app.run(debug=True)
Output
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Task is running every 5 seconds Task is running every 5 seconds Task is running every 5 seconds ...
⚠️

Common Pitfalls

  • Not starting the scheduler with start() causes jobs not to run.
  • Forgetting to shut down the scheduler on app exit can cause errors.
  • Running blocking tasks inside scheduled jobs can freeze the app; use lightweight or async tasks.
  • Using Flask's development server with reloader can start multiple schedulers; disable reloader or use production server.
python
from apscheduler.schedulers.background import BackgroundScheduler

def my_task():
    print('Task executed')

scheduler = BackgroundScheduler()

# Wrong: forgetting to start scheduler
scheduler.add_job(func=my_task, trigger='interval', seconds=10)

# Correct:
scheduler.start()
📊

Quick Reference

Use BackgroundScheduler for Flask apps to run tasks in the background. Common triggers:

  • interval: run every fixed time period
  • date: run once at a specific time
  • cron: run periodically with cron-like syntax

Always start the scheduler and shut it down properly.

Key Takeaways

Use APScheduler's BackgroundScheduler to schedule tasks in Flask.
Always call scheduler.start() to activate scheduled jobs.
Avoid blocking operations inside scheduled tasks to keep the app responsive.
Shut down the scheduler gracefully when the Flask app stops.
Disable Flask debug reloader or use production server to prevent multiple schedulers.