【问题标题】:How to receive celery tasks from another module如何从另一个模块接收 celery 任务
【发布时间】:2018-04-29 02:33:16
【问题描述】:

我可以从我的主应用程序成功接收 celery 任务 - 但是,我的系统无法从另一个模块接收任务。我在一个远程 Ubuntu 服务器上,使用主管 for celery。

draft1 是我的主应用程序,post 是另一个模块(我无法从中接收任务的模块)。

draft1/__init__.py

#This will make sure the app is always imported when
#Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ['celery_app']

draft1/celery.py

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'draft1.settings')

app = Celery("draft1", broker=CELERY_BROKER_URL, include=['post'])
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) #post is in my installed apps

draft1/tasks.py

@periodic_task(run_every=timedelta(minutes=1))
def test_job():
    from polls.models import Question
    for i in Question.objects.all():
        if i.question_text == "test":
            i.question_text = "not_test"
            i.save()
    return HttpResponseRedirect('/')


@periodic_task(name='run_scheduled_jobs', run_every=timedelta(seconds=30))
def run_scheduled_jobs():
    return True

post/tasks.py

@periodic_task(name='test_post', run_every=timedelta(seconds=30))
def test_post():
    from .models import Post
    for i in Post.objects.all():
        if i.entered_category == "test":
            i.entered_category = "not_test"
            i.save()
    return HttpResponseRedirect('/')


@periodic_task(name='post_jobs', run_every=timedelta(seconds=30)) # task name found! celery will do its job
def post_jobs():
    # do whatever stuff you do
    return True

settings.py

CELERYBEAT_SCHEDULE = {
    'run_scheduled_jobs': {
        'task': 'run_scheduled_jobs', # the same goes in the task name
        'schedule': timedelta(seconds=45),
    },
    'test_job': {
            'task': 'tasks.test_job',
            'schedule': timedelta(minutes=3),
    },
    'post_jobs': {
        'task': 'post.tasks.post_jobs',  #i've also tried tasks.post_jobs
        'schedule': timedelta(minutes=1),
    },
    'test_post': {
        'task': 'post.tasks.test_post',
        'schedule': timedelta(seconds=45),
    }
}

这是我启动 worker 的命令:celery -A draft1 worker -l info

celery beat 是通过:celery -A draft1 beat -l info --scheduler 启动的。

draft1/tasks.py 的任务是我收到的唯一任务:

这是为什么?

【问题讨论】:

    标签: python django celery supervisord


    【解决方案1】:

    您传递的celery -A 开关显式地为draft1 应用程序创建了一个工作器。您需要为post 应用程序设置一个单独的工作程序,并为该应用程序设置一个celery.py,以便您可以为post 任务创建一个单独的Celery 实例。如果您愿意(您可能会这样做),这些显然可以共享同一个消息代理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      • 1970-01-01
      • 2018-01-20
      • 2017-01-12
      • 2019-05-21
      • 2015-12-25
      • 2021-02-05
      相关资源
      最近更新 更多