$ pip install django
$ pip install django-celery
$ pip freeze
amqp==1.4.8
anyjson==0.3.3
billiard==3.3.0.22
celery==3.1.19
Django==1.9
django-celery==3.1.17
kombu==3.0.30
pytz==2015.7
wheel==0.24.0
1 Erstellen Sie ein Projekt
$ django-admin.py startproject proj
$ python manage.py startapp sampleapp
/c/dev/projects/proj
Bestätigung
|--manage.py
|--proj
| |--__init__.py
| |--settings.py
| |--urls.py
| |--wsgi.py
|--sampleapp
| |--__init__.py
| |--admin.py
| |--apps.py
| |--migrations
| | |--__init__.py
| |--models.py
| |--tests.py
| |--views.py
2 settings
/proj/settings.py
INSTALLED_APPS = (
'djcelery',
'kombu.transport.django',
'sampleapp',
)
# Celery Setting
import djcelery
djcelery.setup_loader()
BROKER_URL = 'django://'
# Tasks will be executed asynchronously.
CELERY_ALWAYS_EAGER = False
/proj/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', 'proj.settings')
from django.conf import settings # noqa
app = Celery('proj')
# 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.conf.update(
CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend',
)
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
/proj/init.py
from __future__ import absolute_import
# 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 # noqa
3 Aufgabenimplementierung
/sampleapp/tasks.py
import time
from celery import task
@task
def add(a, b):
time.sleep(10)
return a + b
4 DB-Initialisierung
$ python manage.py makemigrations djcelery
Migrations for 'djcelery':
0002_auto_20151211_1830.py:
- Alter field status on taskmeta
- Alter field state on taskstate
$ python manage.py migrate djcelery
Operations to perform:
Apply all migrations: djcelery
Running migrations:
Rendering model states... DONE
Applying djcelery.0002_auto_20151211_1830... OK
1 Starten Sie den Sellerie-Arbeiter
$ celery -A proj worker -l info -c 1
2 Laufen Sie von der Django-Shell
$ python manage.py shell
(InteractiveConsole)
>>> from sampleapp.tasks import add
>>> result = add.delay(1, 2)
>>> result.ready()
False
>>> result.ready() #10 Sekunden sind vergangen
True
>>> result.get()
3
Recommended Posts