版本:

celery:3.1.25

django-celery:3.2.2

django:1.8.16


安装celery3

pipinstallcelery==3.1.25pipinstalldjango-celery


celery与django结合使用的配置:

参考文档:http://docs.celeryproject.org/en/3.1/django/first-steps-with-django.html


proj/proj/settings配置:

INSTALLED_APPS=('django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','study','djcelery',)


importdjcelerydjcelery.setup_loader()BROKER_URL='redis://172.16.42.128:6379'CELERYBEAT_SCHEDULER='djcelery.schedulers.DatabaseScheduler'CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend'CELERY_ACCEPT_CONTENT=['application/json']CELERY_TASK_SERIALIZER='json'CELERY_RESULT_SERIALIZER='json'CELERY_TIMEZONE='Asia/Shanghai'CELERY_ENABLE_UTC=FalseCELERYD_CONCURRENCY=10CELERYD_MAX_TASKS_PER_CHILD=5CELERY_SEND_EVENTS=True


proj/proj/__init__.py

from__future__importabsolute_import#Thiswillmakesuretheappisalwaysimportedwhen#Djangostartssothatshared_taskwillusethisapp.from.celeryimportappascelery_app#noqa



proj/proj/celery.py

注意:proj改成你自己项目的名称

from__future__importabsolute_importimportosfromceleryimportCelery#setthedefaultDjangosettingsmoduleforthe'celery'program.os.environ.setdefault('DJANGO_SETTINGS_MODULE','proj.settings')fromdjango.confimportsettings#noqaapp=Celery('proj')#Usingastringheremeanstheworkerwillnothaveto#pickletheobjectwhenusingWindows.app.config_from_object('django.conf:settings')app.autodiscover_tasks(lambda:settings.INSTALLED_APPS)@app.task(bind=True)defdebug_task(self):print('Request:{0!r}'.format(self.request))



demoapp/tasks.py

from__future__importabsolute_importfromceleryimportshared_task@shared_taskdefadd(x,y):returnx+y@shared_taskdefmul(x,y):returnx*y@shared_taskdefxsum(numbers):returnsum(numbers)


命令行启动celery

启动celerycam

pythonmanage.pycelerycam


启动worker

pythonmanage.pyceleryworker-linfo


启动beat

pythonmanage.pycelerybeat-linfo