作者:劉賓向抢, thomas_liub@hotmail.com
請尊重作者著作權(quán)囱怕,轉(zhuǎn)載請注明出處,謝謝!
分布式任務(wù)隊列佳遂,配合Django擴(kuò)展Django異步處理能力。參考資料
1. 安裝celery, 并建立Celery文件
pip install celery
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
app = Celery('proj')
# Using a string here means the worker don't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
2. Django初始化加載
from __future__ import absolute_import, unicode_literals
# 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
__all__ = ['celery_app']
3. 添加任務(wù)
# Create your tasks here
from __future__ import absolute_import, unicode_literals
from celery import shared_task
@shared_task
def add(x, y):
return x + y
@shared_task
def mul(x, y):
return x * y
@shared_task
def xsum(numbers):
return sum(numbers)
4. 啟動worker
celery -A proj worker -l info
5. 周期性調(diào)度
- Crontab調(diào)度
- Solar調(diào)度
1. 安裝celery-beat
pip install django-celery-beat
2. 安裝app
INSTALLED_APPS = (
...,
'django_celery_beat',
)
3. 同步數(shù)據(jù)庫表
python manage.py migrate
4. 啟動
celery -A proj beat -l info -S django