Created
July 29, 2019 20:06
-
-
Save jacobo/0859e34bce0a35d75a10826c41688147 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
class RedisLock | |
class << self | |
def with_lock(name, wait: false) | |
key = "LOCK:#{name}" | |
until fetch_lock(key) | |
if wait | |
sleep(1) | |
else | |
return | |
end | |
end | |
begin | |
Timeout.timeout(13) do # timeout in 13 seconds and delete the lock | |
yield | |
end | |
ensure | |
$redis.del(key) | |
end | |
end | |
def fetch_lock(key) | |
$redis.set(key, 1, nx: true, px: 15_000) # expires in 15 seconds | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment