Why is my Celery configuration not taking effect?
I'm running a Django app with Celery 5.3.4. I'm using Redis as the broker.
I want to configure the task_time_limit and task_time_soft_limit options, but I can't get them to take effect when running locally. I've tried setting them very low, and running a slow task that sleeps for 10 seconds:
app.conf.task_time_limit = 5
app.conf.task_soft_time_limit = 1
But, when running the Celery worker locally, it completes the slow task and doesn't time out:
2024-03-05T15:46:04.647630Z [info ] Task slow_task[97f51f79-ac48-4aa3-9098-a3ec5a299adc] received [celery.worker.strategy]
2024-03-05T15:46:14.741217Z [info ] Task slow_task[97f51f79-ac48-4aa3-9098-a3ec5a299adc] succeeded in 10.093100208323449s: None [celery.app.trace]
I've tried configuring Celery in many different ways. Here's my current config, spread out over 2 files:
celery.py:
import os
from celery import Celery
from celery.signals import worker_init
from django.conf import settings
# Set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kosa_api.settings")
app = Celery("kosa_api")
# 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")
# Load task modules from all registered Django apps.
app.autodiscover_tasks()
app.conf.task_time_limit = 5
app.conf.task_soft_time_limit = 1
settings/celery.py (this is imported in my app's settings):
from kosa_api.settings.utils import get_safe_redis_url
CELERY_WORKER_HIJACK_ROOT_LOGGER = False
REDIS_URL = get_safe_redis_url()
CELERY_BROKER_URL = f"{REDIS_URL}/0"
CELERY_RESULT_BACKEND = f"{REDIS_URL}/2"
# only store results for a while to prevent redis from filling up
CELERY_RESULT_EXPIRES = timedelta(minutes=30)
# in tests, run celery tasks as regular functions
CELERY_TASK_ALWAYS_EAGER = TEST
CELERY_TASK_ACKS_LATE = True
# i tried all of the following, but none took effect:
# CELERY_CELERYD_SOFT_TIME_LIMIT = 1
# CELERY_CELERYD_TIME_LIMIT = 5
# CELERY_TASK_SOFT_TIME_LIMIT = 1
# CELERY_TASK_TIME_LIMIT = 5
What am I doing wrong?
Use as below.
- Inside celery.py file
app.conf.update(
task_soft_time_limit=1,
task_time_limit=5,
)
Or
- Inside django settings.py file
CELERY_TASK_TIME_LIMIT = 5
CELERY_TASK_SOFT_TIME_LIMIT = 1