百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

一篇文章搞定Celery消息队列配置定时任务

liuian 2024-12-01 00:59 43 浏览

介绍

celery 定时器是一个调度器(scheduler);它会定时地开启(kicks off)任务,然后由集群中可用的工人(worker)来执行。

定时任务记录(entries)默认 从 beat_schedule 设置中获取,但自定义存储也可以使用,如把记录存储到SQL数据库中。

要确保同一时间一份时间表上只有一个调度器在运行,否则会因为重复发送任务而结束。使用集中途径意味着定时任务不用必须同步,并且服务无需用锁操控。


  • user:用户程序,用于告知celery去执行一个任务。
  • broker: 存放任务(依赖RabbitMQ或Redis,进行存储)
  • worker:执行任务
  • celery需要rabbitMQ、Redis、Amazon SQS、Zookeeper(测试中) 充当broker来进行消息的接收,并且也支持多个broker和worker来实现高可用和分布式。http://docs.celeryproject.org/en/latest/getting-started/brokers/index.html

    版本和要求

    Celery version 4.0 runs on
            Python ?2.7, 3.4, 3.5?
            PyPy ?5.4, 5.5?
        This is the last version to support Python 2.7, and from the next version (Celery 5.x) Python 3.5 or newer is required.
    
        If you’re running an older version of Python, you need to be running an older version of Celery:
    
            Python 2.6: Celery series 3.1 or earlier.
            Python 2.5: Celery series 3.0 or earlier.
            Python 2.4 was Celery series 2.2 or earlier.
    
        Celery is a project with minimal funding, so we don’t support Microsoft Windows. Please don’t open any issues related to that platform.

    环境准备

    安装rabbitMQ或Redis

    安装celery

    pip3 install celery

    快速上手

    s1.py

    s1.pyimport time
    from celery import Celery
    
    app = Celery('tasks', broker='redis://192.168.10.48:6379', backend='redis://192.168.10.48:6379')
    
    
    @app.task
    def xxxxxx(x, y):
        time.sleep(10)
        return x + y

    s2.py

    from s1 import func
    
    # func,并传入两个参数
    result = xxxxxx.delay(4, 4)
    print(result.id)

    s3.py

    from celery.result import AsyncResult
    from s1 import app
    
    async = AsyncResult(id="f0b41e83-99cf-469f-9eff-74c8dd600002", app=app)
    
    if async.successful():
        result = async.get()
        print(result)
        # result.forget() # 将结果删除
    elif async.failed():
        print('执行失败')
    elif async.status == 'PENDING':
        print('任务等待中被执行')
    elif async.status == 'RETRY':
        print('任务异常后正在重试')
    elif async.status == 'STARTED':
        print('任务已经开始被执行')
    # 执行 s1.py 创建worker(终端执行命令):
    celery worker -A s1 -l info
    # PS:Windows系统上执行命令时出错解决方法
        pip3 install eventlet
    # 后期运行修改为:
        celery worker -A s1 -l info -P eventlet
    # 执行 s2.py ,创建一个任务并获取任务ID:
        python3 s2.py
    
    # 执行 s3.py ,检查任务状态并获取结果:
        python3 s3.py

    多任务结构

    pro_cel
        ├── celery_tasks# celery相关文件夹
        │   ├── celery.py   # celery连接和配置相关文件
        │   └── tasks.py    #  所有任务函数
        ├── check_result.py # 检查结果
        └── send_task.py    # 触发任务

    pro_cel/celery_tasks/celery

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    from celery import Celery
    
    celery = Celery('func',
                    broker='redis://192.168.111.111:6379',
                    backend='redis://192.168.111.111:6379',
                    include=['celery_tasks.tasks'])
    
    # 时区
    celery.conf.timezone = 'Asia/Shanghai'
    # 是否使用UTC
    celery.conf.enable_utc = False

    pro_cel/celery_tasks/tasks.py

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    import time
    from .celery import celery
    
    
    @celery.task
    def func(*args, **kwargs):
        time.sleep(5)
        return "任务结果"
    
    
    @celery.task
    def hhhhhh(*args, **kwargs):
        time.sleep(5)
        return "任务结果"

    pro_cel/check_result.py

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    from celery.result import AsyncResult
    from celery_tasks.celery import celery
    
    async = AsyncResult(id="ed88fa52-11ea-4873-b883-b6e0f00f3ef3", app=celery)
    
    if async.successful():
        result = async.get()
        print(result)
        # result.forget() # 将结果删除
    elif async.failed():
        print('执行失败')
    elif async.status == 'PENDING':
        print('任务等待中被执行')
    elif async.status == 'RETRY':
        print('任务异常后正在重试')
    elif async.status == 'STARTED':
        print('任务已经开始被执行')

    pro_cel/send_task.py

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import celery_tasks.tasks
    
    # 立即告知celery去执行func任务,并传入两个参数
    result = celery_tasks.tasks.func.delay(4, 4)
    
    print(result.id)

    更多配置:http://docs.celeryproject.org/en/latest/userguide/configuration.html

    定时任务

    设定时间让celery执行一个任务

    import datetime
    from celery_tasks.tasks import func
    """
    from datetime import datetime
     
    v1 = datetime(2020, 4, 11, 3, 0, 0)
    print(v1)
     
    v2 = datetime.utcfromtimestamp(v1.timestamp())
    print(v2)
     
    """
    ctime = datetime.datetime.now()
    utc_ctime = datetime.datetime.utcfromtimestamp(ctime.timestamp())
     
    s10 = datetime.timedelta(seconds=10)
    ctime_x = utc_ctime + s10
     
    # 使用apply_async并设定时间
    result = func.apply_async(args=[1, 3], eta=ctime_x)
    print(result.id)

    类似于contab的定时任务

    """
    celery beat -A proj
    celery worker -A proj -l info
     
    """
    from celery import Celery
    from celery.schedules import crontab
     
    app = Celery('tasks', broker='amqp://147.918.134.86:5672', backend='amqp://147.918.134.86:5672', include=['proj.s1', ])
    app.conf.timezone = 'Asia/Shanghai'
    app.conf.enable_utc = False
     
    app.conf.beat_schedule = {
        # 'add-every-10-seconds': {
        #     'task': 'proj.s1.add1',
        #     'schedule': 10.0,
        #     'args': (16, 16)
        # },
        'add-every-12-seconds': {
            'task': 'proj.s1.add1',
            'schedule': crontab(minute=42, hour=8, day_of_month=11, month_of_year=4),
            'args': (16, 16)
        },
    }

    注:如果想要定时执行类似于crontab的任务,需要定制 Scheduler来完成。

    Flask中应用Celery

    pro_flask_celery/
    ├── app.py
    ├── celery_tasks
        ├── celery.py
        └── tasks.py

    app.py

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    from flask import Flask
    from celery.result import AsyncResult
    
    from celery_tasks import tasks
    from celery_tasks.celery import celery
    
    app = Flask(__name__)
    
    TASK_ID = None
    
    
    @app.route('/')
    def index():
        global TASK_ID
        result = tasks.func.delay()
        TASK_ID = result.id
    
        return "任务已经提交"
    
    
    @app.route('/result')
    def result():
        global TASK_ID
        result = AsyncResult(id=TASK_ID, app=celery)
        if result.ready():
            return result.get()
        return "xxxx"
    
    
    if __name__ == '__main__':
        app.run()

    celery_tasks/celery.py

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    from celery import Celery
    from celery.schedules import crontab
    
    celery = Celery('func',
                    broker='redis://192.168.110.148:6379',
                    backend='redis://192.168.110.148:6379',
                    include=['celery_tasks.tasks'])
    
    # 时区
    celery.conf.timezone = 'Asia/Shanghai'
    # 是否使用UTC
    celery.conf.enable_utc = False

    celery_task/tasks.py

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    import time
    from .celery import celery
    
    
    @celery.task
    def hello(*args, **kwargs):
        print('执行hello')
        return "hello"
    
    
    @celery.task
    def func(*args, **kwargs):
        print('执行func')
        return "func"
    
    
    @celery.task
    def hhhhhh(*args, **kwargs):
        time.sleep(5)
        return "任务结果"

    记录

    为了定时调用任务,你必须添加记录到打点列表中:

    from celery import Celery
    from celery.schedules import crontab
    
    app = Celery()
    
    @app.on_after_configure.connect
    def setup_periodic_tasks(sender, **kwargs):
        # 每10秒调用 test('hello') .
        sender.add_periodic_task(10.0, test.s('hello'), name='add every 10')
    
        # 每30秒调用 test('world') 
        sender.add_periodic_task(30.0, test.s('world'), expires=10)
    
        # 每周一上午7:30执行
        sender.add_periodic_task(
            crontab(hour=7, minute=30, day_of_week=1),
            test.s('Happy Mondays!'),
        )
    
    @app.task
    def test(arg):
        print(arg)

    用on_after_configure处理器进行这些设置意味着当使用test.s()时我们不会在模块层面运行app 。

    add_periodic_task() 函数在幕后会添加记录到beat_schedule设定,同样的设定可以用来手动设置定时任务:

    例子: 每30秒运行 tasks.add .

    app.conf.beat_schedule = {
        'add-every-30-seconds': {
            'task': 'tasks.add',
            'schedule': 30.0,
            'args': (16, 16)
        },
    }
    app.conf.timezone = 'UTC'

    一般会使用配置文件进行配置,如下
    celeryconfig.py:

    broker_url = 'pyamqp://'
    result_backend = 'rpc://'
    
    task_serializer = 'json'
    result_serializer = 'json'
    accept_content = ['json']
    timezone = 'Europe/Oslo'
    enable_utc = True
    beat_schedule = {
        'add-every-30-seconds': {
            'task': 'tasks.add',
            'schedule': 30.0,
            'args': (16, 16)
        },
    }

    程序里使用

    app.config_from_object('celeryconfig')
    
    注意
    如果你的参数元组里只有一个项目,只用一个逗号就可以了,不要圆括号。

    时间表使用时间差意味着每30秒间隔会发送任务(第一个任务在celery定时器开启后30秒发送,然后上每次距一次运行后30秒发送一次)

    可使用的属性

    task:要执行的任务名字

    schedule:执行的频率[可以是整数秒数,时间差,或者一个周期( crontab)。你也可以自 定义你的时间表类型,通过扩展schedule接口]

    args:位置参数 (list 或 tuple)

    kwargs:键值参数 (dict)

    options:执行选项 (dict)[这可以是任何被apply_async()支持的参数与—-exchange, routing_key, expires,等]

    relative:如果 relative 是 true ,时间表“由时钟时间”安排,意味着 频率近似到最近的秒,分钟,小时或天,这取决于时间差中的时间间隔[默认relative是false,频率不会近似,会相对于celery的启动时间]

    Crontab 表达式语法


    开启调度

    开启celery定时服务

    celery -A proj beat

    可以把定时器嵌入到工人(worker)中,通过启用workers -B选项,如果你永远不会运行超过一个工人节点这就会很方便。但这不太常见,不推荐在生产环境这样使用

    celery -A proj worker -B

    定时器需要在本地数据库文件(默认名为 celerybeat-schedule )存储任务上次运行时间,所以它需要在当前目录中写权限。或者你也可以给这个文件指定一个位置

    celery -A proj beat -s /home/celery/var/run/celerybeat-schedule

    #Python##每天学python##Python入门推荐#




    相关推荐

    Python生态下的微服务框架FastAPI

    FastAPI是什么FastAPI是一个用于构建API的web框架,使用Python并基于标准的Python类型提示。与flask相比有什么优势高性能:得益于uvloop,可达到与...

    SpringBoot:如何解决跨域问题,详细方案和示例代码

    跨域问题在前端开发中经常会遇到,特别是在使用SpringBoot框架进行后端开发时。解决跨域问题的方法有很多,我将为你提供一种详细的方案,包含示例代码。首先,让我们了解一下什么是跨域问题。跨域是指在...

    使用Nginx轻松搞定跨域问题_使用nginx轻松搞定跨域问题的方法

    跨域问题(Cross-OriginResourceSharing,简称CORS)是由浏览器的同源策略引起的。同源策略指的是浏览器限制来自不同源(协议、域名、端口)的JavaScript对资源的...

    spring boot过滤器与拦截器的区别

    有小伙伴使用springboot开发多年,但是对于过滤器和拦截器的主要区别依然傻傻分不清。今天就对这两个概念做一个全面的盘点。定义与作用范围过滤器(Filter):过滤器是一种可以动态地拦截、处理和...

    nginx如何配置跨域_nginx配置跨域访问

    要在Nginx中配置跨域,可以使用add_header指令来添加Access-Control-Allow-*头信息,如下所示:location/api{if($reques...

    解决跨域问题的8种方法,含网关、Nginx和SpringBoot~

    跨域问题是浏览器为了保护用户的信息安全,实施了同源策略(Same-OriginPolicy),即只允许页面请求同源(相同协议、域名和端口)的资源,当JavaScript发起的请求跨越了同源策略,...

    图解CORS_图解数学

    CORS的全称是Cross-originresourcesharing,中文名称是跨域资源共享,是一种让受限资源能够被其他域名的页面访问的一种机制。下图描述了CORS机制。一、源(Orig...

    CORS 幕后实际工作原理_cors的工作原理

    跨域资源共享(CORS)是Web浏览器实施的一项重要安全机制,用于保护用户免受潜在恶意脚本的攻击。然而,这也是开发人员(尤其是Web开发新手)感到沮丧的常见原因。小编在此将向大家解释它存在...

    群晖无法拉取Docker镜像?最稳定的方法:搭建自己的加速服务!

    因为未知的原因,国内的各大DockerHub镜像服务器无法使用,导致在使用群晖时无法拉取镜像构建容器。网上大部分的镜像加速服务都是通过Cloudflare(CF)搭建的,为什么都选它呢?因为...

    Sa-Token v1.42.0 发布,新增 API Key、TOTP 验证码等能力

    Sa-Token是一款免费、开源的轻量级Java权限认证框架,主要解决:登录认证、权限认证、单点登录、OAuth2.0、微服务网关鉴权等一系列权限相关问题。目前最新版本v1.42.0已...

    NGINX常规CORS错误解决方案_nginx配置cors

    CORS错误CORS(Cross-OriginResourceSharing,跨源资源共享)是一种机制,它使用额外的HTTP头部来告诉浏览器允许一个网页运行的脚本从不同于它自身来源的服务器上请求资...

    Spring Boot跨域问题终极解决方案:3种方案彻底告别CORS错误

    引言"接口调不通?前端同事又双叒叕在吼跨域了!""明明Postman能通,浏览器却报OPTIONS403?""生产环境跨域配置突然失效,凌晨3点被夺命连环Ca...

    SpringBoot 项目处理跨域的四种技巧

    上周帮一家公司优化代码时,顺手把跨域的问题解决了,这篇文章,我们聊聊SpringBoot项目处理跨域的四种技巧。1什么是跨域我们先看下一个典型的网站的地址:同源是指:协议、域名、端口号完全相...

    Spring Cloud入门看这一篇就够了_spring cloud使用教程

    SpringCloud微服务架构演进单体架构垂直拆分分布式SOA面向服务架构微服务架构服务调用方式:RPC,早期的webservice,现在热门的dubbo,都是RPC的典型代表HTTP,HttpCl...

    前端程序员:如何用javascript开发一款在线IDE?

    前言3年前在AWSre:Invent大会上AWS宣布推出Cloud9,用于在云端编写、运行和调试代码,它可以直接运行在浏览器中,也就是传说中的WebIDE。3年后的今天随着国内云计算的发...