不同文件中的Celery + Redis任务

nik*_*328 5 python celery

当我从命令行运行Celery时,我只能看到与Celery对象在同一文件中的任务,而看不到其他文件中的任务。

该项目的结构如下:

celery_test
    celery_tasks
        __init__.py
        celery_app.py
        async
            __init__.py
            tasks.py
        marker
            __init__.py
            tasks.py
Run Code Online (Sandbox Code Playgroud)

文件内容如下

celery_app.py

from __future__ import absolute_import
from celery import Celery

celery_application = Celery('celery_test', backend='redis://localhost', broker='redis://localhost')

@celery_application.task
def test_celery():
    print 4
Run Code Online (Sandbox Code Playgroud)

而且任何tasks.py文件都有这样的东西

async/tasks.py

from __future__ import absolute_import
import time

from celery_tasks.celery_app import celery_application


@celery_application.task
def async_test():
    print 'Start async_test'
    time.sleep(3)
    print 'Finish async_test'
Run Code Online (Sandbox Code Playgroud)

当我如下运行芹菜

celery --app=celery_tasks.celery_app:celery_application worker -l debug
Run Code Online (Sandbox Code Playgroud)

我得到以下

 -------------- celery@LAPTOP-HCR4G00Q v3.1.25 (Cipater)
---- **** -----
--- * ***  * -- Windows-10-10.0.16299
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app:         celery_test:0x6ff3f28
- ** ---------- .> transport:   redis://localhost:6379//
- ** ---------- .> results:     redis://localhost/
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ----
--- ***** ----- [queues]
 -------------- .> celery           exchange=celery(direct) key=celery


[tasks]
  . celery.backend_cleanup
  . celery.chain
  . celery.chord
  . celery.chord_unlock
  . celery.chunks
  . celery.group
  . celery.map
  . celery.starmap
  . celery_tasks.celery_app.test_celery
Run Code Online (Sandbox Code Playgroud)

那只是与应用程序在同一文件中的任务。

关于如何解决的任何建议?我真的需要按主题分开任务,因为它们很多,所以它们在一个文件中。

nik*_*328 9

我花了很多时间写这个问题,我刚刚解决了它,所以我分享了这个解决方案,因为没有太多关于它的信息(或者至少我没有找到它)。

定义 Celery 对象后,我曾尝试自动发现任务,但没有奏效。我的最后一次尝试是通过以下方式更改应用程序的名称和强制检测:

celery_application.autodiscover_tasks(['celery_tasks.async', 'celery_tasks.marker'], force=True)

celery_test/运行:

celery --app=celery_tasks.celery_app:celery_application worker -l info

那解决了我的问题。我希望这可以帮助你