Environment preparation
- Python3.6
- Pip Install django==2.0.1
- Pip Install celery==4.1.0
- Pip Install Eventlet (join the co-process support)
- Installing Erlang and Rabbitmq-server
Configuring the settings.py File
- In the settings.py file, add the following:
...LANGUAGE_CODE = ‘zh-hans‘TIME_ZONE = ‘Asia/Shanghai‘USE_I18N = TrueUSE_L10N = TrueUSE_TZ = FalseCELERY_BROKER_URL = ‘amqp://guest:[email protected]:5672‘
Create celery.py in settings.py sibling directory
- celery.py
- Note replacement: Project_Name
# -*- coding: utf-8 -*-from __future__ import absolute_import, unicode_literalsimport osfrom celery import Celery# 设置环境变量os.environ.setdefault(‘DJANGO_SETTINGS_MODULE‘, ‘project_name.settings‘)# 注册Celery的APPapp = Celery(‘project_name‘)# 绑定配置文件app.config_from_object(‘django.conf:settings‘, namespace=‘CELERY‘)# 自动发现各个app下的tasks.py文件app.autodiscover_tasks()
Modify the init.py file for the settings.py sibling directory
from __future__ import absolute_import, unicode_literalsfrom .celery import app as celery_app__all__ = [‘celery_app‘]
Create a tasks.py file in an app
# -*- coding: utf-8 -*-from celery.task import task# 自定义要执行的task任务@taskdef print_hello(): return ‘hello celery and django...‘
Configure recurring tasks or Scheduled tasks
- Edit the settings.py file again to add the following:
- Configuration format for timed tasks reference: http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html
from celery.schedules import crontabCELERY_BEAT_SCHEDULE = { # 周期性任务 ‘task-one‘: { ‘task‘: ‘app.tasks.print_hello‘, ‘schedule‘: 5.0, # 每5秒执行一次 # ‘args‘: () }, # 定时任务 ‘task-two‘: { ‘task‘: ‘app.tasks.print_hello‘, ‘schedule‘: crontab(minute=0, hour=‘*/3,10-19‘), # ‘args‘: () }}
Start worker and Scheduled tasks
- Start worker (switch to manage.py sibling directory execution)
-A project_name worker -l info -P eventlet
- Start a scheduled task or recurring task
-A project_name beat -l info
- Background to start a scheduled task or recurring task
Celery Multi start w1-a fushentang-l info-p Eventlet
The extension that holds the result of the task
pip install django-celery-results
- Install APP
INSTALLED_APPS = ( ..., ‘django_celery_results‘,)
- To generate a database table:
python manage.py migrate django_celery_results
- Configuration settings:
CELERY_RESULT_BACKEND = ‘django-db‘
(use database to hold task execution result information)
"Python" Django2.0 integrated Celery4.1 detailed