django-Celery非同期およびタイミングタスクの実装
1.環境
Celery>=4.0この環境でエラーが発生します.この環境での使用は推奨されません.
2.インストール
3.Redisをインストールし、Brokerとして使用する(RabbitMQ公式推奨だが、インストールが面倒な点)
4.djangoプロジェクトの新規作成
公式ドキュメント配置 新規ファイル 新規 編集 は、 である.
adminバックグラウンドでの構成構成 adminバックグラウンドにログイン構成
1つの djangoとceleryを起動し、ログ を表示します.
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
# Djcelery
Crontabs # linux crontab
Intervals #
Periodic tasks #
Tasks
Workers
1つの
periodic task
タスク内容app.tasks.cus_task
を構成するcrontab
またはinterval
設定で5 sごとに1回実行するcelery -A Demo worker -l debug
#
celery -A Demo beat -l debug --max-interval=10 # 10s djcelery