django celery实现分布式任务 + beat 实现定时任务 + redis

文章介绍了如何在Django项目中安装和配置Celery框架,以及利用redis作为中间件和结果存储,实现分页式任务和定时任务。同时提到了eventlet作为并发库支持Celery的并发模式,并展示了创建定时任务的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、安装方法

# 安装celery 框架 实现分页式任务高度
pip install celery
# 使python与redis 数据库实现连接,若在linux可能要单独下载安装,低版本的redis不兼容celery
pip install redis
# 基于celery基础上封装的分页式任务功能,主要适用于django
pip install django-celery-results
# 基于celery基础上封装的定时任务功能, 主要用于djano
pip install djanto-celery-beat
# python的协程并发库,这是celery实现分页式的并发模式之一
pip install eventlet

二、目录

创建一个django项目(项目名:celery4)和app(app名:app)

.
├── app # app 
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── celery4 # 项目
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
└── templates

三、配置celery

  • 在项目下(celery4目录下,和settings.py同级)新建celery.py
    celery.py
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery4.settings') # 项目名.settings

app = Celery('celery4') # 项目名

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
  • 配置定时任务
    settings.py
from celery.schedules import crontab
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/11' # redis作为中间件
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/12' # 数据结果存储地址
from datetime import timedelta

CELERY_BEAT_SCHEDULE = {
    'celery4_text': { # 任务名(随意起)
        'task': 'app.tasks.text', # 定时任务函数路径
        'schedule': timedelta(seconds=30), # 任务循环时间
        "args": (4,9), # 参数
},
  • 在app下新建tasks.py文件(一定要是tasks.py)
from celery import shared_task
from app.models import xxx # 数据库,方便显示
from datetime import datetime

def write_celery_to_record(tips):
	"""更新文件"""
    project_path = os.path.dirname(os.path.abspath(__file__))
    file_path = project_path + r'\celery.txt'
    now = datatime.now().strftime("%H:%M:%S")
    with open(file_path, "a") as f:
        f.write(tips + ',时间:' + now)
        f.write("\n")
        f.close()

@shared_task
def text(a,b):
	write_celery_to_record('执行任务')
    c = a+b
    xxx.objects.create(
        name = c,
        tim = now
    ) # 每执行一次,就会生成一条数据


    return "我是celery4.3"


参考:
https://blog.youkuaiyun.com/Coxhuang/article/details/86921407
https://blog.youkuaiyun.com/Coxhuang/article/details/89763076
https://blog.youkuaiyun.com/Coxhuang/article/details/89058429

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值