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")
  • は、djangoおよびceleryを起動する
  • である.
    # 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
    

    1つのperiodic taskタスク内容app.tasks.cus_taskを構成するcrontabまたはinterval設定で5 sごとに1回実行する
  • djangoとceleryを起動し、ログ
  • を表示します.
    celery -A Demo worker -l debug
    
    #      
    celery -A Demo beat -l debug --max-interval=10  #  10s    djcelery