zoukankan      html  css  js  c++  java
  • python 关于celery的异步任务队列的基本使用(celery+redis)【采用配置文件设置】

    工程结构说明:源文件下载请访问https://i.cnblogs.com/Files.aspx

    __init__.py:实例化celery,并加载配置模块

    celeryconfig.py:配置模块

    task1:任务1,实现加法

    task2:任务2,实现乘法

    app.py:应用,任务生产者

    1、__init__.py:实例化celery,并加载配置模块

    # -*- coding: utf-8 -*-
    
    from celery import Celery
    
    myapp=Celery('demo')
    
    #通过Celery实例加载配置模块celeryconfig.py
    myapp.config_from_object('celerywithconfig.celeryconfig') 

     2、celeryconfig.py:配置模块

    # -*- coding: utf-8 -*-
    
    '''
    Created on 2019年8月28日
    
    @author: lenovo
    '''
    BROKER_URL='redis://localhost:6379/1'
    
    CELERY_RESULT_BACKEND='redis://localhost:6379/2'
    
    CELERY_TIMEZONE='Asia/Shanghai'#不指定时区的话默认采用UTC
    
    #导入指定的任务模块
    CELERY_IMPORTS=(
        'celerywithconfig.task1',
        'celerywithconfig.task2',
        )

    3、task1:任务1,实现加法

    # -*- coding: utf-8 -*-
    
    '''
    Created on 2019年8月28日
    
    @author: lenovo
    '''
    import time
    
    #从__init__.py中导入实例化的Celery myapp
    from celerywithconfig import myapp
    
    @myapp.task
    def add(x,y):
        time.sleep(3)
        return x+y

    4、task2:任务2,实现乘法

    # -*- coding: utf-8 -*-
    
    '''
    Created on 2019年8月28日
    
    @author: lenovo
    '''
    import time
    from celerywithconfig import myapp
    
    @myapp.task
    def multiply(x,y):  
        time.sleep(4)
        return x * y

    5、app.py:应用,任务生产者

    # -*- coding: utf-8 -*-
    
    '''
    Created on 2019年8月28日
    
    @author: lenovo
    '''
    from celerywithconfig import task1
    from celerywithconfig import task2
    
    task1.add.delay(2, 4)
    task2.multiply.delay(4, 5)
    print 'end...'

    6、启动worker,监听任务

    cd到src路径下,执行命令python -m celery -A celerywithconfig worker --loglevel=info

    7、执行app.py,生产任务

    8、查看任务消费情况:worker日志显示同时接收到了2个任务,并分别进行了消费:

    9、查看任务消费情况:消费结果成功保存在backend中: 

  • 相关阅读:
    第三章-5、图片左右滑动(动态面板引导页面)
    第三章-8、抽屉导航(动态面板)
    第三章-7、没做
    第三章-6、失败
    第三章-4、瀑布流(动态面板)
    第三章-3、跳转页面&返回页面
    第三章-2、设置条件进行外部连接,跳转页面
    第三章-1、界面原件属性使用(登录界面)
    6、如何将excel表格中的图片批量居中对齐
    React Native
  • 原文地址:https://www.cnblogs.com/apple2016/p/11422388.html
Copyright © 2011-2022 走看看