插件窝 干货文章 Django+Nginx+uWSGI定时任务怎么实现

Django+Nginx+uWSGI定时任务怎么实现

任务 crontab Django Celery 619    来源:    2025-04-25

Django + Nginx + uWSGI 定时任务实现方案

在 Django 项目中结合 Nginx 和 uWSGI 部署时,实现定时任务有以下几种主要方法:

1. 使用 Django 的第三方包 django-crontab

安装

pip install django-crontab

配置

settings.py 中添加:

INSTALLED_APPS = [
    ...
    'django_crontab',
    ...
]

CRONJOBS = [
    ('*/5 * * * *', 'myapp.cron.my_scheduled_job'),
    ('0 0 * * *', 'django.core.management.call_command', ['clearsessions']),
]

使用方法

  • 添加任务:python manage.py crontab add
  • 查看任务:python manage.py crontab show
  • 移除任务:python manage.py crontab remove

2. 使用 Celery 实现异步任务调度

安装

pip install celery django-celery-beat

配置

settings.py 中添加:

INSTALLED_APPS = [
    ...
    'django_celery_beat',
    ...
]

CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERY_TIMEZONE = 'Asia/Shanghai'

创建任务

tasks.py 中:

from celery import shared_task
from celery.schedules import crontab
from celery.task import periodic_task

@periodic_task(run_every=crontab(hour=7, minute=30, day_of_week=1))
def every_monday_morning():
    print("This runs every Monday morning at 7:30am!")

启动 Celery

celery -A your_project worker -l info -B

3. 使用 Linux 系统的 crontab

直接使用系统的 crontab 来调用 Django 管理命令:

# 编辑 crontab
crontab -e

# 添加如下内容(每5分钟运行一次)
*/5 * * * * /path/to/venv/bin/python /path/to/manage.py your_command

4. 使用 APScheduler

安装

pip install apscheduler

在 Django 项目中初始化

from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore

scheduler = BackgroundScheduler()
scheduler.add_jobstore(DjangoJobStore(), "default")

# 添加任务
scheduler.add_job(my_job, 'interval', minutes=5)

scheduler.start()

注意事项

  1. uWSGI 的特殊考虑

    • 如果使用 uWSGI 的 Emperor 模式,确保定时任务只在主进程中运行一次
    • 可以使用 --enable-threads 选项允许线程运行
  2. Nginx 配置

    • 对于需要 HTTP 触发的定时任务,可以配置 Nginx 路由到特定视图
    • 示例配置: nginx location /run-task/ { include uwsgi_params; uwsgi_pass unix:/path/to/yourproject.sock; }
  3. 日志记录

    • 确保定时任务有完善的日志记录
    • 可以配置 Django 的 logging 系统或直接写入文件
  4. 并发问题

    • 如果任务可能长时间运行,考虑使用锁机制防止重复执行
    • 可以使用 django-pglocks 或其他锁机制

选择哪种方案取决于你的具体需求: - 简单任务:django-crontab 或系统 crontab - 复杂调度:Celery 或 APScheduler - 需要分布式任务:Celery 是最佳选择