Created
          October 11, 2019 20:26 
        
      - 
      
- 
        Save eduzen/6db2abbb9b9fcc16683f3d7f3bfebfba to your computer and use it in GitHub Desktop. 
    Ensuring a task is only executed one at a time
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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