简体   繁体   中英

Celery Function not called

I try to create a progress bar with celery. Unfortunately my worker function get not called.

def checkconfig_post_new (request):
    job = do_work.delay()
    print ("Work started")
    return HttpResponseRedirect ( reverse ( 'poll_state' ) + '?job=' + job.id )


# this decorator is all that's needed to tell celery this is a worker task
@task()
def do_work():
    for i in range(10):
        sleep(0.1)
        print (i)
        current_task.update_state(state='PROGRESS',
            meta={'current': i, 'total': 10})

The print statement "Work started" will never be printed out. Also the "i" will never be printed.

It seems, that the program will stop working.

Here is the full code:

celery.py

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'devadmin.settings')

app = Celery('devadmin')

# 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 app configs.
app.autodiscover_tasks()


@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

__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 .celery import app as celery_app

__all__ = ('celery_app',)

views.py

from celery import task, current_task
from celery.result import AsyncResult
from time import sleep

def checkconfig_post_new (request):
    job = do_work.delay()
    print ("Work started")
    return HttpResponseRedirect ( reverse ( 'poll_state' ) + '?job=' + job.id )

tasks.py

@task()
    def do_work():
        for i in range(10):
            sleep(0.1)
            print (i)
            current_task.update_state(state='PROGRESS',
                meta={'current': i, 'total': 10})

1st, check the registered tasks of your's worker (launch it 2x, sometimes its empty the 1st print).

from celery.task.control import  inspect
i = inspect()
i.registered_tasks()

2nd you need to put your task in a tasks.py , because autodiscover_tasks search this pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM