Django设置异步任务

1、安装Django-celery 包:pip install django-celery==3.2.2

2、开启redis服务

  需要使用redis做broker,所以在使用异步和定时任务时需要开启redis服务器

3、配置信息

  

  在INSTALLED_APPS引入模块

  

      配置具体信息

# 自定义异步
import djcelery
djcelery.setup_loader()
# BROKER_URL = 'django://' # 使用django做broker,消息代理、队列
BROKER_URL = 'redis://10.255.0.250:6379/4'  # 使用redid做broker,消息代理、队列
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'  # 这是使用了django-celery默认的数据库调度模型,任务执行周期都被存在你指定的orm数据库中
# BROKER_POOL_LIMIT = 0
CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend'  # 需要跟踪任务的状态时保存结果和状态,结果存储
# CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/2'
CELERY_TIMEZONE = 'Asia/Shanghai'  # 默认上海时区
CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
# 调度任务
from datetime import timedelta
from celery.schedules import crontab

CELERYBEAT_SCHEDULE = {
    # 定时任务
    'daybreake': {
        'task': 'emall_app.tasks.add',
        'schedule': crontab(minute=u'1', hour=u'0'),
        'args': (2, 3)
    },
    # 定期任务
    'add-every-3-secondes': {
        'task': 'emall_app.tasks.add',
        'schedule': timedelta(seconds=10),
        'args': (5, 5)
    },

}

 具体的异步任务的方法(如果想在别的模块用到异步,就必须在各个模块的目录中创建task.py文件ps:文件名必须是这个,在这个模块中写方法)

@task
def add(x, y):
    return x + y

在别的view文件调用

扫描二维码关注公众号,回复: 2179220 查看本文章
from emall_app.tasks import add
from prod_core import constants
from prod_core.decorators import json_response

@json_response
def task_demo(request):
    result = add.delay(2, 2)
    log.exception('=========== result')
    log.exception(result)

    if result.ready():
        print "Task has run"
        if result.successful():
            print "Result was: %s" % result.result
        else:
            if isinstance(result.result, Exception):
                print "Task failed due to raising an exception"
                raise result.result
            else:
                print "Task failed without raising exception"
    else:
        print "Task has not yet run"
    return {'code': constants.RESULT_SUCCESS}

4、启动异步任务

启动broker

celery worker -l info

 

启动心跳:

python manage.py celery beat 

注意:启动broker和启动心跳必须是在两个不同的终端,每次添加异步任务时都必须重新开启心跳和开启broker。且先把根目录下的celerybeat.pid删除

猜你喜欢

转载自www.cnblogs.com/wuyan717/p/9317041.html
今日推荐