# Configuration is easy, just configure the location of your Redis database: app.conf.broker_url = 'redis://localhost:6379/0'
# Where the URL is in the format of: redis://:password@hostname:port/db_number
# all fields after the scheme are optional, and will default to localhost on port 6379, using database 0.
如果想获取每个任务的执行结果,还需要配置一下把任务结果存在哪
1 2
# If you also want to store the state and return values of tasks in Redis, you should configure these settings: app.conf.result_backend = 'redis://localhost:6379/0'
>>> result = add.delay(4,'a') >>> result.get(propagate=False) # propagate=False 不触发异常,获取错误信息 TypeError("unsupported operand type(s) for +: 'int' and 'str'",) >>> result.traceback # 获取具体错误信息 log打印用 'Traceback (most recent call last):\n File "/usr/local/python3.5/lib/python3.5/site-packages/celery/app/trace.py", line 367, in trace_task\n R = retval = fun(*args, **kwargs)\n File "/usr/local/python3.5/lib/python3.5/site-packages/celery/app/trace.py", line 622, in __protected_call__\n return self.run(*args, **kwargs)\n File "/data/celerys/tasks.py", line 12, in add\n return x+y\nTypeError: unsupported operand type(s) for +: \'int\' and \'str\'\n'
在项目中如何使用celery
可以把celery配置成一个应用,目录格式如下
1 2 3
proj/__init__.py /celery.py /tasks.py
proj/celery.py内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# proj/celery.py from __future__ import absolute_import, unicode_literals from celery import Celery
daemonization 脚本使用 Celery multi 命令在后台启动一个或多个worker
1 2 3 4
$ celery multi start w1 -A proj -l info celerymulti v4.0.0 (latentcall) > Starting nodes... > w1.halcyon.local: OK
重启
1 2 3 4 5 6 7 8 9 10
$ celery multi restart w1 -A proj -l info celery multi v4.0.0 (latentcall) > Stopping nodes... > w1.halcyon.local: TERM -> 64024 > Waiting for 1 node..... > w1.halcyon.local: OK > Restarting node w1.halcyon.local: OK celery multi v4.0.0 (latentcall) > Stopping nodes... > w1.halcyon.local: TERM -> 64052
# proj/proj/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery
# set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
app = Celery('proj')
# Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY')
# Load task modules from all registered Django app configs. app.autodiscover_tasks()