How to cancel an already executing task with celery and Python?

Estimated read time 2 min read

Celery is a powerful task queue library that allows you to run asynchronous tasks in your Python applications. Sometimes, you may want to cancel a task that is already executing due to some reason. Here’s how you can cancel an already executing task with Celery in Python:

  1. Install the necessary dependencies: To use Celery in your Python application, you will first need to install the Celery library using pip. You may also need to install a message broker such as RabbitMQ or Redis to handle message passing between the Celery worker and the client.
  2. Create a Celery task: Define a Celery task that you want to cancel. For example:
from celery import Celery

app = Celery('tasks', broker='pyamqp://guest@localhost//')

@app.task
def long_running_task():
    # some long running task
    pass
  1. Trigger the task: Trigger the task by calling it asynchronously using apply_async() method.
task = long_running_task.apply_async()
  1. Cancel the task: To cancel the task, you can use the revoke() method on the task object returned by apply_async(). The revoke() method will send a signal to the Celery worker to stop executing the task.
task.revoke(terminate=True)

The revoke() method takes an optional terminate argument that specifies whether the task should be terminated immediately or allowed to finish before termination. If terminate is set to True, the Celery worker will immediately stop the task’s execution.

Note that the ability to cancel a task depends on the task’s implementation. If the task doesn’t check for cancellation signals periodically, it may continue running even after receiving a cancellation signal. Therefore, it’s important to make sure your tasks are designed to handle cancellation properly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply