标签:amp cron 方式 amqp image append sleep pip module
Celery 官网:http://www.celeryproject.org/
Celery 官方文档英文版:http://docs.celeryproject.org/en/latest/index.html
Celery 官方文档中文版:http://docs.jinkan.org/docs/celery/
Celery本身不提供消息服务,但是可以方便的和第三方提供的消息中间件集成。包括,RabbitMQ, Redis等等
Worker是Celery提供的任务执行的单元,worker并发的运行在分布式的系统节点中。
Task result store用来存储Worker执行的任务的结果,Celery支持以不同方式存储任务的结果,包括AMQP, redis等
异步任务:将耗时操作任务提交给Celery去异步执行,比如发送短信/邮件、消息推送、音视频处理等等
定时任务:定时执行某件事情,比如每天数据统计
pip install celery
消息中间件:RabbitMQ/Redis
app=celery.Celery(‘任务名‘, broker=‘xxx‘, backend=‘xxx‘, include=[‘xxx‘, ‘xxx‘])
project ├── celery_task # celery包 │ ├── __init__.py # 包文件 │ ├── celery.py # celery连接和配置相关文件,且名字必须交celery.py │ └── tasks.py # 所有任务函数 ├── add_task.py # 添加任务 └── get_result.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‘])
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
from celery_task import tasks # 添加立即执行任务 t1 = tasks.add.delay(10, 20) t2 = tasks.low.delay(100, 50) print(t1.id) # 添加延迟任务 from datetime import datetime, timedelta def eta_second(second): ctime = datetime.now() utc_ctime = datetime.utcfromtimestamp(ctime.timestamp()) time_delay = timedelta(seconds=second) return utc_ctime + time_delay tasks.low.apply_async(args=(200, 50), eta=eta_second(10))
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(‘任务已经开始被执行‘)
# 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)添加任务:自动添加任务,所以要启动一个添加任务的服务 # 命令:celery beat -A celery_task -l info # 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‘]) # 时区 app.conf.timezone = ‘Asia/Shanghai‘ # 是否使用UTC app.conf.enable_utc = False # 任务的定时配置 from datetime import timedelta from celery.schedules import crontab app.conf.beat_schedule = { ‘low-task‘: { ‘task‘: ‘celery_task.tasks.low‘, ‘schedule‘: timedelta(seconds=3), # ‘schedule‘: crontab(hour=8, day_of_week=1), # 每周一早八点 ‘args‘: (300, 150), } }
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
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(‘任务已经开始被执行‘)
# 重点:要将 项目名.settings 所占的文件夹添加到环境变量 # import sys # sys.path.append(r‘项目绝对路径‘) # 开启django支持 import os os.environ.setdefault(‘DJANGO_SETTINGS_MODULE‘, ‘项目名.settings‘) import django django.setup() # 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)添加任务:自动添加任务,所以要启动一个添加任务的服务 # 命令:celery beat -A celery_task -l info # 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‘]) # 时区 app.conf.timezone = ‘Asia/Shanghai‘ # 是否使用UTC app.conf.enable_utc = False # 任务的定时配置 from datetime import timedelta from celery.schedules import crontab app.conf.beat_schedule = { ‘django-task‘: { ‘task‘: ‘celery_task.tasks.test_django_celery‘, ‘schedule‘: timedelta(seconds=3), ‘args‘: (), } }
from .celery import app from home.models import Banner from settings.const import BANNER_COUNT # 轮播图最大显示条数 from home.serializers import BannerModelSerializer from django.core.cache import cache @app.task def update_banner_list(): # 获取最新内容 banner_query = Banner.objects.filter(is_delete=False, is_show=True).order_by(‘-orders‘)[:BANNER_COUNT] # 序列化 banner_data = BannerModelSerializer(banner_query, many=True).data for banner in banner_data: banner[‘image‘] = ‘http://127.0.0.1:8000‘ + banner[‘image‘] # 更新缓存 cache.set(‘banner_list‘, banner_data) return True
""" url: 发送短信的接口/email/, 发送者地址 与 发送信息 (发送的时间) 视图类: EmailAPIView - post post逻辑: 1. 交给celery异步立即执行: 拿到celery_task包中的任务, 调用delay就可以将任务交给celery异步执行 2. 定时发送短信(延迟到指定时间发送): 拿到celery_task包中的任务, 根据发送时间确定延迟执行的时间, 调用apply_async延迟执行 定时任务: 定时爬虫, 定时更新(接口缓存更新) """
标签:amp cron 方式 amqp image append sleep pip module
原文地址:https://www.cnblogs.com/KrisYzy/p/11774398.html