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中: 

  • 相关阅读:
    [t]淘宝幻灯片上下滑动效果
    [t]手风琴效果
    [t]仿FLASH的图片轮换效果
    [t]新浪微博自动加载信息
    图片加载问题
    [t]照片墙
    Best Of My Renderings
    My car renderings
    Silverlight后台CS代码中创建四种常用的动画效果
    Silverlight、SVG、WPF转换工具
  • 原文地址:https://www.cnblogs.com/apple2016/p/11422388.html
Copyright © 2011-2022 走看看