Flask
Python
Scheduling
Background Tasks
Web Development

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

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Flask, a lightweight WSGI web application framework in Python, is often used for web development due to its simplicity and flexibility. However, web applications often require specific tasks to run at regular intervals. For example, you might want to clear expired sessions, send notification emails, or update data from an API every hour. To accomplish this, you can schedule functions to automatically execute on a set schedule, such as hourly. This guide will explore methods to schedule functions in a Flask application using popular scheduling tools.

Methods to Schedule Functions

1. Using APScheduler

One popular and versatile library for scheduling tasks in Python applications is APScheduler. It provides many options to schedule jobs, such as cron-like scheduling, interval-based, and one-time execution.

Installation

First, ensure that APScheduler is installed:

bash
pip install apscheduler

Basic Configuration

Here's a simple implementation for scheduling a function to run every hour using Interval scheduling:

python
1from flask import Flask
2from apscheduler.schedulers.background import BackgroundScheduler
3import atexit
4
5app = Flask(__name__)
6scheduler = BackgroundScheduler()
7
8def scheduled_task():
9    print("This task runs every hour.")
10
11# Schedule the task
12scheduler.add_job(func=scheduled_task, trigger="interval", hours=1)
13
14# Start the scheduler
15scheduler.start()
16
17# Shut down the scheduler when exiting the app
18atexit.register(lambda: scheduler.shutdown())
19
20@app.route('/')
21def home():
22    return "Welcome to the Flask Scheduler!"
23
24if __name__ == "__main__":
25    app.run()

2. Using Celery with Redis or RabbitMQ

For more robust solutions, especially in production environments where distributed task execution is required, Celery is the go-to option. It's an asynchronous task queue/job queue that you can use with services like Redis or RabbitMQ.

Installation

bash
pip install celery
pip install redis

Configuration

Here's a step-by-step to set up Celery that executes a task every hour with Flask:

  1. Create a tasks.py file for your Celery tasks:
python
1    from celery import Celery
2    import time
3
4    app = Celery('tasks', broker='redis://localhost:6379/0')
5
6    @app.task
7    def hourly_task():
8        print("This task runs every hour.")
  1. Create a celeryconfig.py if you need custom settings. Specify time zones, task serialization preferences, etc.
  2. Schedule the Celery Task using Celery Beat:
    Create and configure the celery_tasks.py:
python
1    from celery import Celery
2    from celery.schedules import crontab
3
4    app = Celery('tasks', broker='redis://localhost:6379/0', backend='redis://localhost:6379/0')
5
6    app.conf.beat_schedule = {
7        'hourly-task': {
8            'task': 'tasks.hourly_task',
9            'schedule': crontab(minute=0, hour='*'),
10        },
11    }
12    
13    app.conf.timezone = 'UTC'

3. Other Methods

  • Cron Jobs: If you prefer not to use Python libraries for scheduling, you can set up cron jobs on your server.
  • Systemd Timers: For Linux environments, using systemd timers is another efficient way to schedule recurring tasks.

Key Points Summary

MethodIdeal Use CaseSupported FeaturesRequires External Service
APSchedulerSmall to medium Flask applicationsInterval, cron, one-time executionNo
Celery with Redis/RabbitMQScalability, distributed environmentsAsynchronous task execution, retries, schedulingYes
Cron JobsServer-level scheduling, scriptsPrecise time schedulingNo
Systemd TimersLinux cron alternativeDependency control, integrates with systemdNo

Conclusion

The choice of method to schedule your Flask function every hour depends on your specific needs. For lightweight applications, APScheduler offers simplicity and ease of integration with Flask. On the other hand, Celery is ideal for handling complex tasks in a distributed system, despite requiring more setup. Lastly, traditional Unix-like options like cron jobs or systemd timers provide robust and simple alternatives outside the application scope.

By understanding these methods, you can choose the most appropriate way to schedule your functions and enhance your application's functionality efficiently.


Course illustration
Course illustration

All Rights Reserved.