celery + django:
异步任务:
from celery import Celery
broker = 'redis://127.0.0.1:6379/0'
backend = 'redis://127.0.0.1:6379/1'
app = Celery(broker=broker, backend=backend)
@app.task
def add(a, b):
res = a + b
print('a + b = %s' % res)
return res
from tasks import add
result = add.delay(x,y)
print(reult.id)
from tasks import app
from celery.result import AsyncResult
id = 'ad4ca85d-998a-4cc9-9d24-655986a169b3'
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('任务已经开始被执行')
延时任务:
from celery_task.tasks import add
from datetime import datetime, timedelta
result = add.apply_async(args=(10, 20), eta=datetime.utcnow() + timedelta(seconds=10))
print(result)
from celery_task.celery import app
from celery.result import AsyncResult
id = 'f9d97749-7e48-4b56-a31c-69fe73f9c1a7'
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('任务已经开始被执行')
django-celery:
基本使用
django中使用celery有两种方式:
上面建立特定目录结构的是一种,
另一种django-celery模块,对于django版本有严格的要求,要是项目换了环境,就无法使用
安装需要的版本:
celery==3.1.25
django-celery==3.1.20
celery_config.py:
import djcelery
djcelery.setup_loader()
CELERY_IMPORTS=(
'app01.tasks',
)
CELERYD_FORCE_EXECV=True
CELERYD_CONCURRENCY=4
CELERY_ACKS_LATE=True
CELERYD_MAX_TASKS_PER_CHILD=100
CELERYD_TASK_TIME_LIMIT=12*30
task.py:
from celery import task
@task
def add(a,b):
with open('a.text', 'a', encoding='utf-8') as f:
f.write('a')
print(a+b)
views.py:
from django.shortcuts import render,HttpResponse
from app01.tasks import add
from datetime import datetime
def test(request):
ctime = datetime.now()
utc_ctime = datetime.utcfromtimestamp(ctime.timestamp())
from datetime import timedelta
time_delay = timedelta(seconds=5)
task_time = utc_ctime + time_delay
result = add.apply_async(args=[4, 3], eta=task_time)
print(result.id)
return HttpResponse('ok')
settings.py:
INSTALLED_APPS = [
...
'djcelery',
'app01'
]
...
from djagocele import celeryconfig
BROKER_BACKEND='redis'
BOOKER_URL='redis://127.0.0.1:6379/1'
CELERY_RESULT_BACKEND='redis://127.0.0.1:6379/2'
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(三):用.NET IoT库
· 【非技术】说说2024年我都干了些啥