3

I am trying to write Django command that will cancel existing celery task in my Django application. The idea is to use this command in APIView so user can cancel the task that is already running.

When running python manage.py cancel_task I see in terminal that task was cancelled but the status of the task remains the same and it continues doing the task. In the end the status of the task is always SUCCESS.

The task is opening playwright chromium and going through list of websites.

Task 0d5ffdd3-3a2c-4f40-a135-e1ed353afdf9 has been cancelled.

Below is my command that I store in cancel_task.py

from django.core.management.base import BaseCommand
from celery.result import AsyncResult
from myapp.celery import app as myapp


class Command(BaseCommand):
    help = 'Cancel a long-running Celery task'

    def add_arguments(self, parser):
        parser.add_argument('task_id', help='ID of the task to cancel')

    def handle(self, *args, **options):
        task_id = options['task_id']
        result = AsyncResult(task_id, app=myapp)
        if result.state not in ('PENDING', 'STARTED'):
            self.stdout.write(self.style.WARNING(f'Task {task_id} is not running.'))
            return
        result.revoke(terminate=True, wait=False)
        self.stdout.write(self.style.SUCCESS(f'Task {task_id} has been cancelled.'))

I checked all answers in this post and in this post as well but nothing works in my application.

What am I doing wrong and how to cancel task. I tried to use revoke directly in celery like this:

>>> from myapp.celery import myapp
>>> myapp.control.revoke(task_id, terminate=True)

But the final effect is the same. I get information that the task was cancelled but status does not change.

Adrian
  • 725
  • 4
  • 18

0 Answers0