Celery
pip3 install celery
Celery是一个简单、灵活且可靠的,处理大量消息的分布式系统,专注于实时处理的异步任务队列,同时也支持任务调度。
组成
- 消息中间件(rabbitmq,redis)
- 任务执行单元
- 任务执行结果存储(redis)
执行命令语法
celery worker -A celery_app_task -l info
celery worker -A celery_app_task -l info -P eventlet
异步执行
单目录
定义任务 celery_task.py
import celery
import time
broker = 'redis://127.0.0.1:6379/1'
backend = 'redis://127.0.0.1:6379/2'
cel = celery.Celery('test', backend=backend, broker=broker)
@cel.task
def send_email(name):
print('发邮件')
time.sleep(5)
print('完成%s' % name)
return 'ok'
创建任务执行 produce_task.py
from celery_task import send_email
result = send_email.delay("yuan")
print(result.id)
result2 = send_email.delay("alex")
print(result2.id)
获取结果 get_res.py
from celery.result import AsyncResult
from celery_task import cel
async_result=AsyncResult(id="c6ddd5b7-a662-4f0e-93d4-ab69ec2aea5d", app=cel)
if async_result.successful():
result = async_result.get()
print(result)
# result.forget() # 将结果删除
elif async_result.failed():
print('执行失败')
elif async_result.status == 'PENDING':
print('任务等待中被执行')
elif async_result.status == 'RETRY':
print('任务异常后正在重试')
elif async_result.status == 'STARTED':
print('任务已经开始被执行')
多目录
celery worker -A celery_task -l info -P eventlet
- celery.py: 写配置
- task1 task2 : 写任务
- get_res : 获取结果
- produce_taks : 生产任务
celery.py 配置
from celery import Celery
cel = Celery('celery_demo',
broker='redis://127.0.0.1:6379/1',
backend='redis://127.0.0.1:6379/2',
# 包含以下两个任务文件,去相应的py文件中找任务,对多个任务做分类
include=['celery_tasks.task1',
'celery_tasks.task2'
])
# 时区
cel.conf.timezone = 'Asia/Shanghai'
# 是否使用UTC
cel.conf.enable_utc = False
定义任务 task1 task2
from celery_tasks.celery import cel
import time
@cel.task
def send_msg(name):
print('短信')
time.sleep(5)
print('完成%s' % name)
return "短信"
创建任务执行 product_task
from celery_tasks.task1 import send_msg
from celery_tasks.task2 import send_email
# 立即告知celery去执行test_celery任务,并传入一个参数
result = send_email.delay('yuan')
print(result.id)
result = send_msg.delay('yuan')
print(result.id)
获取结果 get_res.py
from celery.result import AsyncResult
from celery_tasks.celery import cel
while True:
async_result = AsyncResult(id=input(">>"), app=cel)
if async_result.successful():
result = async_result.get()
print(result)
# result.forget() # 将结果删除
elif async_result.failed():
print('执行失败')
elif async_result.status == 'PENDING':
print('任务等待中被执行')
elif async_result.status == 'RETRY':
print('任务异常后正在重试')
elif async_result.status == 'STARTED':
print('任务已经开始被执行')
定时任务
单目录
celery_task.py
from celery_tasks.celery import cel
import time
@cel.task
def send_msg(name):
print('短信')
time.sleep(5)
print('完成%s' % name)
return "短信"
produce_task.py(邮件运行)
from celery_task import send_email
from datetime import datetime
# 方式一 某一固定时间
# v1 = datetime(2020, 3, 11, 16, 19, 00)
# print(v1)
# v2 = datetime.utcfromtimestamp(v1.timestamp())
# print(v2)
# result = send_email.apply_async(args=["egon",], eta=v2)
# print(result.id)
# 方式二 固定时间以后
ctime = datetime.now()
# 默认用utc时间
utc_ctime = datetime.utcfromtimestamp(ctime.timestamp())
from datetime import timedelta
time_delay = timedelta(seconds=10)
task_time = utc_ctime + time_delay
# 使用apply_async并设定时间
result = send_email.apply_async(args=["egon"], eta=task_time)
print(result.id)
get_Res.py
from celery.result import AsyncResult
from celery_task import cel
async_result=AsyncResult(id="c6ddd5b7-a662-4f0e-93d4-ab69ec2aea5d", app=cel)
if async_result.successful():
result = async_result.get()
print(result)
# result.forget() # 将结果删除
elif async_result.failed():
print('执行失败')
elif async_result.status == 'PENDING':
print('任务等待中被执行')
elif async_result.status == 'RETRY':
print('任务异常后正在重试')
elif async_result.status == 'STARTED':
print('任务已经开始被执行')
多目录
和 produce_task.py 没关系
celery.py
from datetime import timedelta
from celery import Celery
from celery.schedules import crontab
cel = Celery('tasks', broker='redis://127.0.0.1:6379/1', backend='redis://127.0.0.1:6379/2', include=[
'celery_tasks.task01',
'celery_tasks.task02',
])
cel.conf.timezone = 'Asia/Shanghai'
cel.conf.enable_utc = False
cel.conf.beat_schedule = {
# 名字随意命名
'add-every-10-seconds': {
# 执行tasks1下的test_celery函数
'task': 'celery_tasks.task01.send_email',
# 每隔2秒执行一次
# 'schedule': 1.0,
# 'schedule': crontab(minute="*/1"),
'schedule': timedelta(seconds=6),
# 传递参数
'args': ('张三',)
},
# 'add-every-12-seconds': {
# 'task': 'celery_tasks.task01.send_email',
# 每年4月11号,8点42分执行
# 'schedule': crontab(minute=42, hour=8, day_of_month=11, month_of_year=4),
# 'args': ('张三',)
# },
}
produce_task.py 命令
此时和produce无关
通过命令来启动
celery beat -A celery_tasks
进程会读取配置文件的内容,周期性的将配置中到期需要执行的任务发送给任务队列
周期性的向队列插入任务