0

I have been trying to set up my scheduled task to run every x minutes, but I am not making any progress. I read the documentation and tried different approaches to the problem but I am obviously still doing something wrong.

celery.py

CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERY_BROKER_URL = 'redis://localhost:6379/1'

from datetime import timedelta
from celery import Celery


app = Celery('taskscheduler', broker=CELERY_BROKER_URL, backend=CELERY_RESULT_BACKEND)


app.autodiscover_tasks()

CELERYBEAT_SCHEDULE = {
    'schedule-name': {
        'task': 'taskscheduler.task.just_print',
        'schedule': timedelta(seconds=5),
    },
}

task.py

from celery import shared_task

@shared_task
def just_print():
    print("Print from celery task")

__init__.py

from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from taskscheduler.celery import app as celery_app

__all__ = ['celery_app']

All of the files are inside one of the many apps folders. What I am trying to achieve is basically to set up this task when I start the server and run it every x seconds, as long as the server is on.

Small Update

I changed my files a little to: celery.py

from __future__ import absolute_import
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERY_BROKER_URL = 'redis://localhost:6379/1'
from django.apps import apps
from datetime import timedelta
from celery import Celery
from celery.task.base import periodic_task


CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler"
app = Celery('taskscheduler', broker=CELERY_BROKER_URL, backend=CELERY_RESULT_BACKEND)


app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()])


@periodic_task(run_every=timedelta(seconds=5))
def just_print():
    print("Print from celery task")

When the function is in celery.py rather than task.py all works fine. However, I want to do it the proper way and make it available from task.py

Adrian Grzywaczewski
  • 868
  • 1
  • 12
  • 25
  • Celery beat is required for scheduled tasks. Are you starting a celery beat process? – jordanm Mar 03 '18 at 00:58
  • @jordanm thanks for the reply. Yeah, I am starting the celery beat process. I noticed one thing that if I have my function inside celery.py it works fine. It does not work however while it's in tasks.py where it has to be. – Adrian Grzywaczewski Mar 03 '18 at 01:03
  • 1
    I think you need to rename your task file as `tasks.py` (with an `s`) – Panu Tangchalermkul Mar 03 '18 at 02:12
  • @PanuTangchalermkul Thanks for the comment, but that did not help. The application still can't find that function. I reckon something is wrong with my autodiscover function? – Adrian Grzywaczewski Mar 04 '18 at 10:34
  • Just to double-check, the app containing `tasks.py` is listed in the `INSTALLED_APPS` in `settings.py`? – Will Keeling Mar 16 '18 at 12:12

0 Answers0