Celery Singleton is a Python library that provides a base class for Celery tasks, ensuring that only one instance of a specific task can be queued or running at any given time. It achieves this by using Redis for distributed locking, leveraging the task's name and arguments to determine uniqueness. The current version is 0.3.1, released in January 2021, and its development appears to be in maintenance with recent activity on its GitHub issues.
pip install celery-singletonVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to define a Celery task as a singleton using `celery-singleton`. It shows that subsequent calls to `delay()` with identical arguments will return the `AsyncResult` of the already queued or running task, rather than queuing a new one. Ensure your Celery app is configured with a Redis broker and result backend.
Ensure all `*args` and `**kwargs` for tasks based on `Singleton` are JSON serializable. For complex objects, pass their IDs and re-fetch them within the task.
Configure `app.conf.singleton_backend_url = 'redis://your_redis_host:port/db'` in your Celery application settings if Redis is not your default broker/backend.
Always set a `lock_expiry` on your singleton tasks, e.g., `@celery_app.task(base=Singleton, lock_expiry=300)`. The `lock_expiry` should be slightly longer than your task's expected maximum runtime.
Refactor your task to accept only JSON-serializable data (e.g., IDs, strings, numbers, lists, dictionaries). If you need to work with complex objects, pass their unique identifiers and load the full object within the task body.
If you want to handle duplicates by receiving the `AsyncResult` of the existing task instead of an error, remove `raise_on_duplicate=True` from your task decorator. If you explicitly want to prevent queuing and catch the error, ensure your calling code handles `DuplicateTaskError`.
Ensure all singleton tasks have a `lock_expiry` set to prevent permanent stale locks. Check your Celery and `celery-singleton` Redis backend configurations. Manually clear stale locks from your Redis instance if necessary, using `DEL <lock_key>` where `<lock_key>` typically includes the task name and arguments hash.