繁体   English   中英

Celery Django 调用.delay() 后任务挂起

[英]Celery task hangs after calling .delay() in Django

从 django 应用程序调用导入任务的.delay()方法时,进程卡住,请求永远不会完成。

我们也没有在控制台上收到任何错误。 使用 pdb 设置set_trace()会产生同样的结果。

审查了以下问题,但没有帮助解决问题:

调用celery任务挂起延迟和apply_async

celery.delay 挂起(最近,不是身份验证问题)

例如。:

后端/settings.py

CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", RABBIT_URL)
CELERY_RESULT_BACKEND = os.environ.get("CELERY_BROKER", RABBIT_URL)

后端/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', 'backend.settings')

app = Celery('backend')

app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()


@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

应用程序/tasks.py

import time
from celery import shared_task

@shared_task
def upload_file(request_id):
    time.sleep(request_id)
    return True

应用程序/views.py

from rest_framework.views import APIView

from .tasks import upload_file

class UploadCreateAPIView(APIView):
    # other methods...

    def post(self, request, *args, **kwargs):
        id = request.data.get("id", None)
        # business logic ...
        print("Going to submit task.")
        import pdb; pdb.set_trace()
        upload_file.delay(id)                  # <- this hangs the runserver as well as the set_trace()
        print("Submitted task.")

问题在于使用 Django 设置 celery 应用程序。 我们需要确保在以下文件中导入并初始化了 celery 应用程序:

backend\\__init__.py

from __future__ import absolute_import, unicode_literals

# 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',)

我遇到过这个问题,即 Celery 通过delayapply_async调用可能会无限期地随机挂起程序。 我尝试了所有broker_transport_optionsretry_policy选项让 Celery 恢复,但它仍然发生。 然后我发现这个解决方案通过使用底层 Python 信号处理程序来强制执行块/函数的执行时间限制。

@contextmanager
def time_limit(seconds):
    def signal_handler(signum, frame):
        raise TimeoutException("Timed out!")

    signal.signal(signal.SIGALRM, signal_handler)
    signal.alarm(seconds)
    try:
        yield
    finally:
        signal.alarm(0)

def my_function():
    with time_limit(3):
        celery_call.apply_sync(kwargs={"k1", "v1"}, expires=30)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM