0

I just finished my celery task for my django app, but I'm looking a way now for how to start/stop it through a toggle button on my frontend UI. I know it can do on django-admin(built in). but I want to make it for the app.

like from a typical django view and restapi, you create a function like this:

def start_task and def stop_task and call it through api(URL) to execute it.

How can I do it? Thanks!

Giddsec
  • 43
  • 5

1 Answers1

1

Sure, a task is just a function you need to call to start and if you've got a task_id then you can revoke a task. More on that explain in this answer

I've got an example of starting a task which updates a search index.

@app.task
def update_search():
    """ Update haystack """
    try:
        update_index.Command().handle(
            remove=True, interactive=False, verbosity=2
        )
    except TransportError as e:
        logger.error(e)

This is called from a view which is accessed using an action link in the admin;

class UpdateSearchView(View):
    """
    View called from the admin that updates search indexes.
    Checks the requesting user is a super-user before proceeding.
    """
    admin_index = reverse_lazy('admin:index')

    @staticmethod
    def _update_search(request):
        """Update search index"""
        update_search.delay()
        messages.success(
            request, _('Search index is now scheduled to be updated')
        )

    def get(self, request, *args, **kwargs):
        """Update search, re-direct back the the referring URL"""
        if request.user.is_anonymous() or not request.user.is_superuser:
            raise PermissionDenied

        self._update_search(request)

        # redirect back to the current page (of index if there is no
        # current page)
        return HttpResponseRedirect(request.GET.get('next', self.admin_index))
markwalker_
  • 12,078
  • 7
  • 62
  • 99
  • how, how about it if I got only the `task_name` instead of `task_id`. because task_id changes every execution of that task_name? – Giddsec Jan 11 '21 at 19:37
  • Yeah the ID is obviously just a unique instance of a task running, so that can be revoked. You can't revoke by task name alone. Details here; https://docs.celeryproject.org/en/stable/reference/celery.app.control.html#celery.app.control.Control.revoke – markwalker_ Jan 11 '21 at 21:20