Sha256: fe673cb0d3fb0e6def599a0326d8df843223c74993ea9e87b5654d6d83fb212e

Contents?: true

Size: 1.13 KB

Versions: 3

Compression:

Stored size: 1.13 KB

Contents

class MailManager::Lock
  class MailManager::LockException < Exception
  end
  def self.with_lock(name, timeout=5, max_attempts=1, &block)
    ActiveRecord::Base.connection_pool.with_connection do |connection|
      begin
        lock = get_lock(connection,name,timeout,max_attempts)
        raise MailManager::LockException.new("Failed to obtain lock #{name} in #{timeout} secs") unless lock
        yield lock
      ensure
        is_released = release_lock(connection,name)
        Rails.logger.warn "Warning: lock #{name} not released!" unless is_released.values.include?('1')
      end
    end
  end
  
  private
  
  def self.name_prefix
    "#{MailManager.site_url}-#{Rails.env}"
  end
  
  def self.get_lock(connection,name,timeout,max_attempts)
    attempts = 0
    lock = {}
    while !lock.values.include?('1') and attempts < max_attempts do 
      attempts += 1
      lock = connection.select_one("SELECT GET_LOCK('#{name_prefix}-#{name}',#{timeout})")
    end
    lock.values.detect{|value| value.to_s.eql?('1')}
  end
  
  def self.release_lock(connection,name)
    connection.select_one("SELECT RELEASE_LOCK('#{name_prefix}-#{name}')")
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
mail_manager-0.1.4 lib/mail_manager/lock.rb
mail_manager-0.1.2 lib/mail_manager/lock.rb
mail_manager-0.1.1 lib/mail_manager/lock.rb