三、定时任务


返回

3.1 简单结构

  • 特点时间

    from celery_task import send_mail, send_msg
    from datetime import datetime
    
    # 本地时间
    t1 = datetime(2021, 3, 20, 16, 40, 0)
    print(t1)
    # 转成UTC时间
    t2 = datetime.utcfromtimestamp(t1.timestamp())
    print(t2)
    # 定时任务:apply_async
    res_mail = send_mail.apply_async(args=['mail', ], eta=t2)
    print(res_mail.id)
    res_msg = send_msg.apply_async(args=['msg', ], eta=t2)
    print(res_msg.id)
    
    
  • 延时时间

    from celery_task import send_mail, send_msg
    from datetime import datetime
    from datetime import timedelta
    
    # 本地时间
    local_time = datetime.now()
    print(local_time)
    # 转成UTC时间
    utc_time = datetime.utcfromtimestamp(local_time.timestamp())
    print(utc_time)
    # 延时10s
    time_delay = timedelta(seconds=10)
    task_time = utc_time + time_delay
    # 定时任务:apply_async
    res_mail = send_mail.apply_async(args=['mail', ], eta=task_time)
    print(res_mail.id)
    res_msg = send_msg.apply_async(args=['msg', ], eta=task_time)
    print(res_msg.id)
    
    

3.2 多目录结构 celery_task

  • 启动命令:celery -A celery_task worker -l info

  • 启动定时任务命令:celery -A celery_task beat

  • __init__.py

  • celery.py

    from celery import Celery
    from datetime import timedelta
    
    """
    启动命令:celery -A celery_task worker -l info
        -c 并发数
    启动定时任务命令:celery -A celery_task beat
    """
    
    # redis的16个区,0-15
    backend = 'redis://127.0.0.1/1'  # store 数据库
    broker = 'redis://127.0.0.1/2'  # broker 消息队列,推荐RabbitMQ
    
    cel = Celery('celery_m', backend=backend, broker=broker,
                 # 包含的任务
                 include=[
                     'celery_task.task01',
                     'celery_task.task02',
                 ])
    cel.conf.timezone = 'Asia/Shanghai'  # 时区
    cel.conf.enable_utc = False  # UTC
    
    # 定时任务:key定时任务名、value定时任务
    cel.conf.beat_schedule = {
        'add-every-10s': {
            'task': 'celery_task.task01.send_mail',  # 任务
            # 'schedule': 1.0,  # 1秒钟后
            # 'schedule': crontab(minute="*/1"),  # 每一分钟
            'schedule': timedelta(seconds=6),  # 每6秒钟添加一个任务到消息队列
            'args': ['mail'],  # 参数
        }
    }
    
    
  • task01.py

  • task02.py

返回