Created
April 17, 2013 23:14
-
-
Save shofetim/5408539 to your computer and use it in GitHub Desktop.
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
| @contextmanager | |
| def exploding_redis_mutex(key, timeout=10): | |
| r = redis.Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB) | |
| mutex_key = ('mutex', key) | |
| while not r.setnx(mutex_key, datetime.now()): | |
| val = datetime.strptime(r.get(mutex_key), '%Y-%m-%d %H:%M:%S.%f') | |
| if (datetime.now() - val).seconds > timeout: | |
| r.delete(mutex_key) | |
| else: | |
| raise RedisMutexLockedError("'%s' is already locked in the mutex" % (key,)) | |
| try: | |
| yield True | |
| finally: | |
| r.delete(mutex_key) | |
| del(r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment