标签:http 英文版 进程 backend djang worker rgs cron 邮件
目录
Celery是一个功能完备即插即用的任务队列。它使得我们不需要考虑复杂的问题,使用非常简单。celery看起来似乎很庞大,本章节我们先对其进行简单的了解,然后再去学习其他一些高级特性。 celery适用异步处理问题,当发送邮件、或者文件上传, 图像处理等等一些比较耗时的操作,我们可将其异步执行,这样用户不需要等待很久,提高用户体验。 celery的特点是:
Celery 官网:http://www.celeryproject.org/
Celery 官方文档英文版:http://docs.celeryproject.org/en/latest/index.html
Celery 官方文档中文版:http://docs.jinkan.org/docs/celery/
Celery的架构由三部分组成,消息中间件(message broker)、任务执行单元(worker)和 任务执行结果存储(task result store)组成。
Celery本身不提供消息服务,但是可以方便的和第三方提供的消息中间件集成。包括,RabbitMQ, Redis等等
Worker是Celery提供的任务执行的单元,worker并发的运行在分布式的系统节点中。
如果我们想跟踪任务的状态,Celery需要将结果保存到某个地方。有几种保存的方案可选:SQLAlchemy、Django ORM、Memcached、 Redis、RPC (RabbitMQ/AMQP)。
异步执行:解决耗时任务
延迟执行:解决延迟任务
定时执行:解决周期(周期)任务
pip install celery
消息中间件:RabbitMQ/Redis
app=Celery('任务名', broker='xxx', backend='xxx')
app.conf.beat_schedul
project
├── celery_task # celery包
│ ├── __init__.py # 包文件
│ ├── celery.py # celery连接和配置相关文件,且名字必须交celery.py
│ └── tasks.py # 所有任务函数
├── add_task.py # 添加任务
└── get_result.py # 获取结果
celery.py
# 1)创建app + 任务
# 2)启动celery(app)服务:
# 非windows
# 命令:celery worker -A celery_task -l info
# windows:
# pip3 install eventlet
# celery worker -A celery_task -l info -P eventlet
# 3)添加任务:手动添加,要自定义添加任务的脚本,右键执行脚本
# 4)获取结果:手动获取,要自定义获取任务的脚本,右键执行脚本
from celery import Celery
broker = 'redis://127.0.0.1:6379/1'
backend = 'redis://127.0.0.1:6379/2'
app = Celery(broker=broker, backend=backend, include=['celery_task.tasks'])
tasks.py
from .celery import app
@app.task
def add(a, b):
res = a + b
print('a + b = %s' % res)
return res
@app.task
def reduce(a, b):
res = a - b
print('a - b = %s' % res)
return res
add_task.py
from tasks import add, reduce
result = add.delay(10, 20)
print(result.id)
get_result.py
from tasks import app
from celery.result import AsyncResult
id = 'f3e679c8-ac51-41a7-9bad-72e1ea5b6a96'
if __name__ == '__main__':
async = AsyncResult(id=id, app=app)
if async.successful():
result = async.get()
print(result)
elif async.failed():
print('任务失败')
elif async.status == 'PENDING':
print('任务等待中被执行')
elif async.status == 'RETRY':
print('任务异常后正在重试')
elif async.status == 'STARTED':
print('任务已经开始被执行')
celery.py
from celery import Celery
broker = 'redis://127.0.0.1:6379/14'
backend = 'redis://127.0.0.1:6379/15'
app = Celery(broker=broker, backend=backend, include=['celery_tasks.tasks'])
tasks.py
from .celery import app
@app.task
def add(a, b):
res = a + b
print('a + b = %s' % res)
return res
@app.task
def reduce(a, b):
res = a - b
print('a - b = %s' % res)
return res
add_task.py
from celery_tasks.tasks import add
from datetime import datetime, timedelta
result = add.apply_async(args=(20, 40), eta=datetime.utcnow() + timedelta(seconds=10))
print(result)
celery.py
from celery import Celery
broker = 'redis://127.0.0.1/14'
backend = 'redis://127.0.0.1/15'
app = Celery(broker=broker, backend=backend, include=['celery_task.tasks'])
# 时区
app.conf.timezone = 'Asia/Shanghai'
# 是否使用UTC
app.conf.enable_utc = False
# 任务的定时配置
from datetime import timedelta
from celery.schedules import crontab
app.conf.beat_schedule = {
'add-task': {
'task': 'celery_task.tasks.add',
'schedule': timedelta(seconds=3),
# 'schedule': crontab(hour=8, day_of_week=1), # 每周一早八点
'args': (20, 50)
},
'reduce-task': {
'task': 'celery_task.tasks.reduce',
'schedule': timedelta(seconds=6),
'args': (20, 50)
}
}
tasks.py
from .celery import app
import time
@app.task
def add(n, m):
print(n)
print(m)
time.sleep(10)
print('n+m的结果:%s' % (n + m))
return n + m
@app.task
def low(n, m):
print(n)
print(m)
print('n-m的结果:%s' % (n - m))
return n - m
get_result.py
from celery_task.celery import app
from celery.result import AsyncResult
id = '21325a40-9d32-44b5-a701-9a31cc3c74b5'
if __name__ == '__main__':
async = AsyncResult(id=id, app=app)
if async.successful():
result = async.get()
print(result)
elif async.failed():
print('任务失败')
elif async.status == 'PENDING':
print('任务等待中被执行')
elif async.status == 'RETRY':
print('任务异常后正在重试')
elif async.status == 'STARTED':
print('任务已经开始被执行')
celery配置django缓存
在项目根目录下先建一个包celery_task
,包中先建两个文件 celery.py
和 tasks.py
celery.py
# 一、加载django配置环境
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "luffyapi.settings.dev")
from celery import Celery
broker = 'redis://127.0.0.1:6379/14'
backend = 'redis://127.0.0.1:6379/15'
app = Celery(broker=broker, backend=backend, include=['celery_task.tasks'])
# 时区
app.conf.timezone = 'Asia/Shanghai'
# 是否使用UTC
app.conf.enable_utc = False
# 任务的定时配置
from datetime import timedelta
from celery.schedules import crontab
app.conf.beat_schedule = {
'update-banner-cache': {
'task': 'celery_task.tasks.update_banner_cache',
'schedule': timedelta(seconds=10),
'args': (),
}
}
tasks.py
from .celery import app
# 获取项目中的模型类
from home.models import Banner
from django.core.cache import cache
from django.conf import settings
from home.serializers import BannerModelSerializer
@app.task
def update_banner_cache():
banner_query = Banner.objects.filter(is_delete=False, is_show=True).all()[:settings.BANNER_COUNT]
banner_data = BannerModelSerializer(banner_query, many=True).data
for banner in banner_data:
banner['image'] = '%s%s' % (settings.BASE_URL, banner.get('image'))
cache.set('banner_cache', banner_data)
return True
标签:http 英文版 进程 backend djang worker rgs cron 邮件
原文地址:https://www.cnblogs.com/setcreed/p/12183288.html