class Bunny::HeartbeatSender

Periodically sends heartbeats, keeping track of the last publishing activity.

@private

Public Class Methods

new(transport, logger) click to toggle source

API

# File lib/bunny/heartbeat_sender.rb, line 15
def initialize(transport, logger)
  @transport = transport
  @logger    = logger
  @mutex     = Monitor.new

  @last_activity_time = Time.now
end

Public Instance Methods

signal_activity!() click to toggle source
# File lib/bunny/heartbeat_sender.rb, line 39
def signal_activity!
  @last_activity_time = Time.now
end
start(period = 30) click to toggle source
# File lib/bunny/heartbeat_sender.rb, line 23
def start(period = 30)
  @mutex.synchronize do
    # calculate interval as half the given period plus
    # some compensation for Ruby's implementation inaccuracy
    # (we cannot get at the nanos level the Java client uses, and
    # our approach is simplistic). MK.
    @interval = [(period / 2) - 1, 0.4].max

    @thread = Thread.new(&method(:run))
  end
end
stop() click to toggle source
# File lib/bunny/heartbeat_sender.rb, line 35
def stop
  @mutex.synchronize { @thread.exit }
end

Protected Instance Methods

beat() click to toggle source
# File lib/bunny/heartbeat_sender.rb, line 61
def beat
  now = Time.now

  if now > (@last_activity_time + @interval)
    @logger.debug { "Sending a heartbeat, last activity time: #{@last_activity_time}, interval (s): #{@interval}" }
    @transport.write_without_timeout(AMQ::Protocol::HeartbeatFrame.encode)
  end
end
run() click to toggle source
# File lib/bunny/heartbeat_sender.rb, line 45
def run
  begin
    loop do
      self.beat

      sleep @interval
    end
  rescue IOError => ioe
    @logger.error "I/O error in the hearbeat sender: #{ioe.message}"
    stop
  rescue Exception => e
    @logger.error "Error in the hearbeat sender: #{e.message}"
    stop
  end
end