Skip to content

Instantly share code, notes, and snippets.

@jacobo
Created July 29, 2019 20:06
Show Gist options
  • Save jacobo/0859e34bce0a35d75a10826c41688147 to your computer and use it in GitHub Desktop.
Save jacobo/0859e34bce0a35d75a10826c41688147 to your computer and use it in GitHub Desktop.
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