Fork me on GitHub

celery简单使用

安装

pip install celery

使用

task.py
1
2
3
4
5
6
7
8
9
10
11
12
13
import time
from celery import Celery


broker = 'redis://:auth@ip:6379/2'
backend = 'redis://:auth@ip:6379/3'
app = Celery('task', broker=broker, backend=backend)


@app.task
def add(x, y):
time.sleep(3)
return x+y
app.py
1
2
3
4
5
from task import add

if __name__ == '__main__':
result = add.delay(3, 5)
print(result)

启动
celery -A task worker --loglevel=info

如果报错
ValueError: not enough values to unpack (expected 3, got 0)
安装pip install eventlet
启动
celery -A task worker --loglevel=info -P eventlet

1
2
3
[2019-05-28 15:55:22,299: INFO/MainProcess] Received task: task.add[e1264c8f-187d-4559-addd-a147663103b9]
[2019-05-28 15:55:25,470: INFO/MainProcess] Task task.add[e1264c8f-187d-4559-addd-a147663103b9] succeede
d in 3.172000000020489s: 8

配置文件

celery_app/__init__.py

celery_app/__init__.py
1
2
3
4
5
import time
from celery import Celery

app = Celery('demoo')
app.config_from_object('celery_app.celeryconfig')

celery_app/celeryconfig.py

celery_app/celeryconfig.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from datetime import timedelta
from celery.schedules import crontab

BROKER_URL = 'redis://:pwd@ip:6379/2'
CELERY_RESULT_BACKEND = 'redis://:pwd@ip:6379/3'

CELERY_TIMEZONE = 'Asia/Shanghai'
CELERY_IMPORTS = (
'celery_app.task',
)

CELERYBEAT_SCHEDULE = {
'task': {
'task': 'celery_app.task.add',
# 'schedule': timedelta(seconds=10), # 每10秒发送一次
'schedule': crontab(hour=18, minute=30), # 每天的18:30分发送
'args': ('hello', 'world')
}
}

celery_app/task.py

celery_app/task.py
1
2
3
4
5
6
7
8
9
import time

from celery_app import app


@app.task
def add(x, y):
time.sleep(3)
return x+y

定时任务

celery_app/celeryconfig.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from datetime import timedelta
from celery.schedules import crontab

BROKER_URL = 'redis://:pwd@ip:6379/2'
CELERY_RESULT_BACKEND = 'redis://:pwd@ip:6379/3'

CELERY_TIMEZONE = 'Asia/Shanghai'
CELERY_IMPORTS = (
'celery_app.task',
)

CELERYBEAT_SCHEDULE = {
'task': {
'task': 'celery_app.task.add',
# 'schedule': timedelta(seconds=10), # 每10秒发送一次
'schedule': crontab(hour=18, minute=30), # 每天的18:30分发送
'args': ('hello', 'world')
}
}

beat启动

1
celery -A celery_app beat --loglevel=info

二合一命令

1
celery -B -A celery_app work --loglevel=info

django使用celery

http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#first-steps-with-django

-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!
0%