Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Ensuring a task is only executed one at a time
import redis
REDIS_CLIENT = redis.Redis()
def only_one(function=None, key="", timeout=None):
"""Enforce only one celery task at a time."""
def _dec(run_func):
def _caller(*args, **kwargs):
ret_value = None
have_lock = False
lock = REDIS_CLIENT.lock(key, timeout=timeout)
have_lock = lock.acquire(blocking=False)
if have_lock:
ret_value = run_func(*args, **kwargs)
if have_lock:
return ret_value
return _caller
return _dec(function) if function is not None else _dec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment