在 Flask 项目中使用 Celery 来实现每月定时任务涉及几个关键步骤:配置 Celery,设置定时任务,以及处理任务逻辑。以下是一个详细的指南,包含代码示例,展示如何在 Flask 应用中使用 Celery 来执行每月定时任务。

1. 环境准备

首先,确保你已经安装了 Flask、Celery 和一个消息代理(如 Redis)。你可以通过 pip 安装这些库:

pip install Flask Celery redis

2. 配置 Flask 和 Celery

创建 Flask 应用

首先,创建一个 Flask 应用。在这个应用中,我们将配置 Celery。

# app.py
from flask import Flask
from celery import Celery

def make_celery(app):
    # 创建一个 Celery 实例,并配置为使用 Flask 配置
    celery = Celery(
        app.import_name,
        broker=app.config['CELERY_BROKER_URL'],
        backend=app.config['CELERY_RESULT_BACKEND']
    )
    celery.conf.update(app.config)
    return celery

app = Flask(__name__)

# 配置 Flask 和 Celery
app.config.update(
    CELERY_BROKER_URL='redis://localhost:6379/0',
    CELERY_RESULT_BACKEND='redis://localhost:6379/0'
)

celery = make_celery(app)

3. 定义 Celery 任务

接下来,定义一个 Celery 任务,该任务将在每月定时运行。

# tasks.py
from app import celery
from datetime import datetime

@celery.task
def monthly_task():
    now = datetime.now()
    print(f"Monthly task executed at {now}")
    # 这里可以添加你需要的任务逻辑

4. 配置定时任务

要设置每月定时任务,你需要使用 Celerybeat 计划任务功能。你可以在 Celery 配置中指定定时任务。

创建 celeryconfig.py

创建一个配置文件来设置 Celery beat 调度。

# celeryconfig.py
from celery.schedules import crontab

beat_schedule = {
    'run-monthly-task': {
        'task': 'tasks.monthly_task',
        'schedule': crontab(day_of_month=1, hour=0, minute=0),  # 每月的第一天午夜执行
    },
}
更新 app.py 配置

celeryconfig.py 配置到你的 Celery 实例中。

# app.py
import celeryconfig

app.config.from_object(celeryconfig)

5. 启动 Celery 和 Celery Beat

在命令行中,分别启动 Celery worker 和 Celery beat。

# 启动 Celery worker
celery -A app.celery worker --loglevel=info

# 启动 Celery beat
celery -A app.celery beat --loglevel=info

6. 完整代码示例

以下是完整的示例代码,包括 Flask 配置、Celery 配置、任务定义和定时任务配置。

app.py
from flask import Flask
from celery import Celery
import celeryconfig

def make_celery(app):
    celery = Celery(
        app.import_name,
        broker=app.config['CELERY_BROKER_URL'],
        backend=app.config['CELERY_RESULT_BACKEND']
    )
    celery.conf.update(app.config)
    return celery

app = Flask(__name__)
app.config.update(
    CELERY_BROKER_URL='redis://localhost:6379/0',
    CELERY_RESULT_BACKEND='redis://localhost:6379/0'
)

celery = make_celery(app)
app.config.from_object(celeryconfig)
tasks.py
from app import celery
from datetime import datetime

@celery.task
def monthly_task():
    now = datetime.now()
    print(f"Monthly task executed at {now}")
    # Add your task logic here
celeryconfig.py
from celery.schedules import crontab

beat_schedule = {
    'run-monthly-task': {
        'task': 'tasks.monthly_task',
        'schedule': crontab(day_of_month=1, hour=0, minute=0),  # 每月第一天午夜执行
    },
}

7. 测试和验证

确保 Redis 服务器正在运行。使用以下命令启动 Celery worker 和 Celery beat,然后检查任务是否在预定时间执行。

# 启动 Celery worker
celery -A app.celery worker --loglevel=info

# 启动 Celery beat
celery -A app.celery beat --loglevel=info

你可以在控制台中查看日志以确认任务的执行情况。如果一切配置正确,你将会看到每月定时任务的输出。

小结

通过以上步骤,你可以在 Flask 应用中配置 Celery 来实现每月定时任务。你可以根据需要调整任务逻辑和定时设置。这样,你就能在 Flask 应用中利用 Celery 的强大功能来处理定时任务了。