ionelmc / python-redis-lock

Lock context manager implemented via redis SET NX EX and BLPOP.
https://pypi.python.org/pypi/python-redis-lock
BSD 2-Clause "Simplified" License
551 stars 77 forks source link

Non-blocking auto-renewing context manager lock #121

Closed Danferno closed 1 month ago

Danferno commented 1 month ago

If I understand correctly, using the lock as a context manager forces blocking=True. In my use-case, I'd like to use the auto-renewing context manager lock to make sure the lock is released if the code fails for any reason. The only way I currently see is to first check if the lock can be acquired and then to release it again to be used by the context manager:

lock = Lock(redis, 'my-lock', expire=10)
if lock.locked():
    print('Someone else is already doing this')
    raise Exception
with Lock(redis, 'my-lock', auto_renewal=True, expire=10):
    print('We can do this!')

Ideally, I'd like the following to work:

try:
    with Lock(redis, 'my-lock', auto_renewal=True, expire=10, blocking=False):
        print('We can do this!')
except NotAcquired:
    print('Someone else is already doing this')
Danferno commented 1 month ago

I initially used an acquire>release cycle, but obviously if I just use .locked() then just checking for locked() is at least as elegant as a try: except: cycle