时间限制不适用于Django Celery 5.3.1

j91ykkif  于 11个月前  发布在  Go
关注(0)|答案(1)|浏览(159)

我在celery和django应用程序中尝试time_limit和soft_time_limit功能时遇到了麻烦。

import os

from celery import Celery

# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings')

app = Celery('server')

# Using a string here means the worker doesn'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')
app.conf.update(
    task_soft_time_limit=1,
    task_time_limit=1,
)

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

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

字符串
我有这个celery配置。我正在尝试在django中为celery任务配置时间限制并运行此任务。

from celery import shared_task
from celery.exceptions import SoftTimeLimitExceeded
from celery.signals import task_success, task_failure, task_prerun
import time
from server.celery import app

@shared_task
def scrape(domain: str, route: str = None):
    try:
        time.sleep(5)
        
    except SoftTimeLimitExceeded:
        print("Time Limit")

@task_prerun.connect(sender=scrape)
def scrape_prerun_notifier(task_id=None, task=None, *args, **kwargs):
    print("From task_prerun_notifier ==> Running just before add() executes")

@task_success.connect(sender=scrape)
def scrape_success_notifier(sender=None, result=None, **kwargs):
    print("Success")

    task_id = sender.request.id

@task_failure.connect(sender=scrape)
def scrape_failure_notifier(task_id=None, exception=None, *args, **kwargs):
    print("Failure")


然而,抓取任务总是成功的,没有捕获到任何异常。我也试过修改装饰器,但它也不起作用。
第一个月
我也试过把它添加到django的设置中,但是没用。
CELERYD_TASK_SOFT_TIME_LIMIT = 1CELERY_TASK_SOFT_TIME_LIMIT = 1
这是我如何开始celery 使用命令行。
celery -A server worker -l info --pool=threadscelery -A server worker -l info --pool=solo
我还没有尝试过prefork pool,因为我不知道如何为它启用日志记录。是不是我的配置有什么问题,导致time_limit和soft_time_limit不起作用?非常感谢任何帮助。

jjjwad0x

jjjwad0x1#

task_time_limit上的文档如下:
以秒为单位的任务硬时间限制。当超过此时间时,处理任务的工作线程将被杀死并被新的工作线程替换。
有了一个单独的游泳池,这将意味着celery 杀死自己,所以虽然没有明确说明,我相信时间限制根本不支持单独游泳池。
由于线程不能停止,可能也不支持。

相关问题