class Lita::Timing::Mutex

Constants

DEL_SCRIPT
LOCK_TIMEOUT

Public Class Methods

new(name, redis) click to toggle source
# File lib/lita/timing/mutex.rb, line 18
def initialize(name, redis)
  @name, @redis = name, redis
end

Public Instance Methods

syncronise() { || ... } click to toggle source
# File lib/lita/timing/mutex.rb, line 22
def syncronise(&block)
  token = SecureRandom.hex(10)
  val = nil
  set_with_retry(@name, token, LOCK_TIMEOUT + 1)
  yield
  @redis.eval(DEL_SCRIPT, keys: [@name], argv: [token])
end

Private Instance Methods

set_with_retry(name, token, timeout) click to toggle source
# File lib/lita/timing/mutex.rb, line 32
def set_with_retry(name, token, timeout)
  give_up_at = Time.now + timeout
  loop do
    val = @redis.set(name, token, nx: true, ex: timeout)
    if val
      return true
    elsif Time.now > give_up_at
      raise "Unable to obtain lock for #{@name} after #{LOCK_TIMEOUT + 2} seconds"
    end
    sleep 1
  end
end