django —— Celery实现异步和定时任务

1. 环境

复制代码
python==2.7

djang==1.11.2  # 1.8, 1.9, 1.10应该都没问题

celery-with-redis==3.0  # 需要用到redis作为中间人服务(Broker)
celery==3.1.25  # 安装上面的会自动安装
kombu==3.0.37
billiard==3.3.0.23

django-celery==3.2.2  # celery插件, 实现定时任务
复制代码

 

celery>=4.0 对此环境会有报错, 暂不建议在此环境下使用

 

2. 安装

pip install django==1.11.2 celery-with-redis==3.0 django-celery==3.2.2

 

3. 安装Redis, 用作Broker (RabbitMQ 官方推荐, 但安装麻烦点)

教程很多, 略

 

4. 新建django项目

复制代码
- Demo
  - Demo
    setting.py
    wsgi.py
    urls.py
  - app
    - migrations
    models.py
    views.py
    ...
复制代码

 

  • 配置settings.py
复制代码
INSTALLED_APPS = (
    ...
    'app',
    'djcelery',# django-celery 可以在admin后台定义定时任务, 开始前需要直接migrate
)


BROKER_URL = 'redis://127.0.0.1:6379/0'
BROKER_TRANSPORT = 'redis'

CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'  # 数据库调度
复制代码

 

  • 新建文件Demo/Demo/celery.py
复制代码
from __future__ import absolute_import

import os

from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Demo.settings')

from django.conf import settings  # noqa

app = Celery('Demo')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)


@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))
复制代码

 

 

  • 新建Demo/app/tasks.py

 

from Demo.celery import app

@app.task
def cus_task(*arg):
    print('This is a test task')

 

  • 编辑Demo/app/views.py
from django.shortcuts import render, HttpResponse

from .tasks import cus_task


def index(request):
    cus_task.delay()
    return HttpResponse("Test async task")

 

  • 启动djangocelery
# django
python manage.py runserver

# celery
celery -A Demo worker -l debug

 

 

admin后台中配置celery计划

  • 配置
  • # 如上settings.py中的设置, 后执行
    python manage.py migrate djcelery

  • 登陆admin后台进行配置
  • # Djcelery模块列表
    
    Crontabs  # 同linux crontab
    Intervals  # 间隔
    Periodic tasks  # 周期任务
    Tasks
    Workers

     

  配置一个periodic task任务内容 app.tasks.cus_task 用crontabinterval设置每5s执行一次

 

  • 启动django和celery, 并查看日志
  • celery -A Demo worker -l debug
    
    # 另一个窗口
    celery -A Demo beat -l debug --max-interval=10  # 每10s扫描一次djcelery任务

     

 

nohup 后台启动

nohup celery -A Demo worker -l debug > abc.log &

 

posted on   星河赵  阅读(497)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示