Search code examples
pythondjangocelerydjango-celerycelerybeat

Use function both as view and as a celery task


I use Django 2.2.12 and Celery 4.4.7

I have some functions (e.g.: downloadpictures) that need to be both used as a view and as a scheduled recurring task. What is the best way to set it up ? Below code generates the following error message :

NameError: name 'downloadpictures' is not defined

downloadapp/views.py

def downloadpictures(request=None):
    xxx
    xxx

downloadapp/tasks.py

from downloadapp import downloadpictures

@shared_task
def downloadpicturesregular():
    downloadpictures()

celery_tasks.py

app.conf.beat_schedule = {
    'downloadpictures_regular':
        {
            'task': 'downloadapp.tasks.downloadpicturesregular',
            'schedule': crontab(hour=18, minute=40, day_of_week='thu,sun'),
        },
        },

Solution

  • Typically your views need to know about your tasks while your tasks don't care about the views. If your application fits that assumption, you should pull the logic out into a third module or into the tasks.py function. Then call that function from both the task and view, or call the task from the view.