zoukankan      html  css  js  c++  java
  • django + celery

    首先安装必要的包:

    pip install celery

    pip install redis

    project层:

    setting.py

    BROKER_URL = 'redis://127.0.0.1:6379/1'
    CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/3'
    BROKER_TRANSPORT = 'redis'

    celery.py

    from __future__ import absolute_import  # 解决命名问题
    
    import os
    import django
    
    from celery import Celery
    from django.conf import settings
    
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', '项目名.settings')
    # 设置配置文件
    django.setup()
    
    app = Celery('项目名')
    
    app.config_from_object('django.conf:settings')  # 制定celery配置文件
    app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)  # 任务
    # app.conf.result_backend = 'redis://localhost:6379/2'

    __init__.py

    from __future__ import absolute_import, unicode_literals
    
    # This will make sure the app is always imported when
    # Django starts so that shared_task will use this app.
    from .celery import app as celery_app
    
    __all__ = ('celery_app',)

    现在来到app:

    tasks.py

    from djcelery.celery import app
    
    @app.task
    def send():
        import time
        print('begin')
        time.sleep(5)
        print('end')
        return 25

    views.py

    from django.shortcuts import  HttpResponse
    from .tasks import send
    
    def test(request):
        send.delay()
        return HttpResponse('nihao')

    开启任务:

       celery -A djcelery worker -l debug

  • 相关阅读:
    枚举类型的应用
    动手动脑
    四则运算和验证码--源码
    ATM源码
    javabean+jsp+servlet+jdbc
    四则运算改良
    Java异常
    课后总结
    包装类Integre
    对象验证
  • 原文地址:https://www.cnblogs.com/jiaxiaoxin/p/10831081.html
Copyright © 2011-2022 走看看