djcelery执行异步任务和定时任务
Posted xuqidong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了djcelery执行异步任务和定时任务相关的知识,希望对你有一定的参考价值。
import djcelery from datetime import timedelta djcelery.setup_loader() CELERY_QUEUES = { ‘beat_tasks‘:{ ‘exchange‘:‘beat_tasks‘, ‘exchange_type‘:‘direct‘, ‘binding_key‘:‘beat_tasks‘, }, ‘work_queue‘: { ‘exchange‘: ‘work_queue‘, ‘exchange_type‘: ‘direct‘, ‘binding_key‘: ‘work_queue‘, } } CELERY_DEFAULT_QUEUE = ‘work_queue‘ CELERY_IMPORTS = ( ‘app01.tasks‘, ) # 有些情况可以防止死锁 CELERYD_FORCE_EXECV = True # 设置并发worker数量 CELERYD_CONCURRENCY = 4 # 允许重试 CELERY_ACKS_LATE = True # 每个worker最多执行100个任务被销毁,可以防止内存泄漏 CELERYD_MAX_TASKS_PER_CHILD = 100 # 超时时间 CELERYD_TASK_TIME_LIMIT = 12 * 30 CELERYBEAT_SCHEDULE = { ‘task1‘:{ ‘task‘:‘course-task‘, ‘schedule‘:timedelta(seconds=5), ‘options‘:{ ‘queue‘:‘beat_tasks‘ } } }
# from celery import task import time # @task # def add(x,y): # time.sleep(3) # return x+y from celery.task import Task class CourseTask(Task): name = ‘course-task‘ def run(self, *args, **kwargs): print(‘start course task‘) time.sleep(4) print(‘args={}, kwargs={}‘.format(args, kwargs)) print(‘end course task‘)
from app01.tasks import CourseTask from django.http import JsonResponse def do(request): print(‘start do request‘) # CourseTask.delay() CourseTask.apply_async(args=(‘hello‘,),queue=‘work_queue‘) print(‘end do request‘) return JsonResponse({‘result‘:‘ok‘})
以上是关于djcelery执行异步任务和定时任务的主要内容,如果未能解决你的问题,请参考以下文章