user1367204
user1367204

Reputation: 4797

Django: How to run a celery task only on start up?

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:

Upvotes: 0

Views: 1952

Answers (1)

ACE Fly
ACE Fly

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

Related Questions