Skip to content

Instantly share code, notes, and snippets.

@eduzen
Created October 11, 2019 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eduzen/6db2abbb9b9fcc16683f3d7f3bfebfba to your computer and use it in GitHub Desktop.
Save eduzen/6db2abbb9b9fcc16683f3d7f3bfebfba to your computer and use it in GitHub Desktop.
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):
"""Decorator."""
def _caller(*args, **kwargs):
"""Caller."""
ret_value = None
have_lock = False
lock = REDIS_CLIENT.lock(key, timeout=timeout)
try:
have_lock = lock.acquire(blocking=False)
if have_lock:
ret_value = run_func(*args, **kwargs)
finally:
if have_lock:
lock.release()
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