Reputation: 4797
I have a django app that uses celery to run tasks.
Sometimes, I have a "hard shutdown" and a bunch of models aren't cleaned up.
I created a task called clean_up
that I want to run on start up.
Here is the tasks.py
from my_app.core import utils
from celery import shared_task
@shared_task
def clean_up():
f_name = clean_up.__name__
utils.clean_up()
Here is what celery.py
looks like:
import os
from celery import Celery
from celery.schedules import crontab
from datetime import timedelta
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_app.settings")
app = Celery("proj")
app.config_from_object("django.conf:settings", namespace="CELERY")
# Load task modules from all registered Django apps.
app.autodiscover_tasks()
app.conf.beat_schedule = {
"runs-on-startup": {
"task": "my_app.core.tasks.clean_up",
"schedule": timedelta(days=1000),
},
}
@app.task(bind=True)
def debug_task(self):
print(f"Request: {self.request!r}")
How can I change celery.py
to run clean_up
only on start up?
Extra info:
docker compose down
docker compose up
Upvotes: 0
Views: 1952
Reputation: 482
you were looking for signal:
tasks.py
add following code:
from celery import signals
@signals.worker_ready.connect
def clean(**kwargs):
...
loggert.info('worker_ready')
Upvotes: 1