Celery regular tasks go into detail

Celery regular tasks go into detail

A. Directory Structure

任务所在目录
    ├── celery_task # celery包 如果celery_task只是建了普通文件夹__init__可以没有,如果是包一定要有
    │   ├── __init__.py # 包文件 看情况要不要存在
    │   ├── celery.py   # celery连接和配置相关文件,且名字必须交celery.py,其实也不是必须的不然你指令可能要修改
    │   └── tasks.py    # 所有任务函数

II. Configuration

celery.py

from celery import Celery


#创建一个Celery对象
broker = 'redis://127.0.0.1:6379/2'  #任务放在用redis://ip:端口/第几个数据库
backend = 'redis://127.0.0.1:6379/3' #任务结果放在
include = ['celery_task.tasks',]    #任务所在目录
app = Celery(broker=broker, backend=backend, include=include)

app.conf.timezone = 'Asia/Shanghai'  #配置时区
app.conf.enable_utc = False      # 是否使用UTC

from datetime import timedelta
from celery.schedules import crontab
app.conf.beat_schedule = {
    #任务名称自定义可随意
    'get_banner-task': { 
        'task': 'celery_task.tasks.get_baidu_info',#任务所在路径且指定哪个任务
        'schedule': crontab(hour=3,minute=0),  #定时任务相关
    },
}

celery.py

from .celery import app
import requests
@app.task  #一定要加装饰器
def get_baidu_info():
    response = requests.get(https://www.baidu.com/')
    return response.text

III. Configuration Parameters

Configuration Parameters way

方式一

app.conf. Parameter Name Parameter Value =

方法二

app.conf.update(
    参数名称=参数值,
    参数名称=参数值
)

方法三

Import Profiles

app.config_from_object('配置文件路径')

Profiles

参数名称=参数值
参数名称=参数值

A. Time Zone Configuration

Common Chinese

app.conf.timezone = 'Asia/Shanghai' 
app.conf.enable_utc = False 
#也可以直接设置
app.conf.timezone = 'Asia/Shanghai' 

International Time

app.conf.enable_utc = True
app.conf.timezone = 'Europe/London'
#也可以直接设置
app.conf.timezone = 'Europe/London'

二.beat_schedule

  • task: Specify the task name
  • schedule: the task scheduler is set to be the second is an integer, may be a timedelta object or objects is a crontab (described later), in short, it is how to set the task repeatedly performed
  • args: location parameter tasks in a list form
  • kwargs: keyword arguments task to form dictionary
  • options: All apply_async supported parameters

timedelta objects

from datetime import timedelta

 'schedule': timedelta(seconds=3), #每三秒 执行一次 其他想想就知道啦
  #具体有啥参数我也不想列举了你ctrl+左键进入timedelta源码自己看就知道啦

crontab objects

#schedule配置举例
from celery.schedules import crontab
# 每分钟执行一次
crontab()

# 每天凌晨十二点执行
crontab(minute=0, hour=0)

# 每十五分钟执行一次
crontab(minute='*/15')

# 每周日的每一分钟执行一次
crontab(minute='*',hour='*', day_of_week='sun')

# 每周三,五的三点,七点和二十二点没十分钟执行一次
crontab(minute='*/10',hour='3,17,22', day_of_week='thu,fri')

Guess you like

Origin www.cnblogs.com/pythonywy/p/11665791.html