Class: DeadBro::Monitor

Inherits:
Object
  • Object
show all
Defined in:
lib/dead_bro/monitor.rb

Constant Summary collapse

SLEEP_INTERVAL_SECONDS =
60

Instance Method Summary collapse

Constructor Details

#initialize(client: DeadBro.client) ⇒ Monitor

Returns a new instance of Monitor.



7
8
9
10
11
12
13
# File 'lib/dead_bro/monitor.rb', line 7

def initialize(client: DeadBro.client)
  @client = client
  @thread = nil
  @running = false
  @stop_mutex = Mutex.new
  @stop_cv = ConditionVariable.new
end

Instance Method Details

#startObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/dead_bro/monitor.rb', line 15

def start
  # Live thread already running — nothing to do.
  return if @running && @thread&.alive?

  # Reset: handles post-fork where @running=true but the thread is dead.
  @running = false

  return unless DeadBro.configuration.enabled

  @running = true
  @thread = Thread.new do
    Thread.current.abort_on_exception = false
    loop do
      break unless @running

      begin
        collect_and_send_stats
      rescue => e
        log_error("Error collecting stats: #{e.message}")
      end

      # Interruptible sleep — stop() signals the CV so shutdown doesn't
      # block up to a full minute. Still naps the full interval during
      # normal operation.
      @stop_mutex.synchronize do
        @stop_cv.wait(@stop_mutex, SLEEP_INTERVAL_SECONDS) if @running
      end
    end
  end

  @thread
end

#stopObject



48
49
50
51
52
53
# File 'lib/dead_bro/monitor.rb', line 48

def stop
  @running = false
  @stop_mutex.synchronize { @stop_cv.broadcast }
  @thread&.join(5) # Safety timeout in case the thread is mid-flight
  @thread = nil
end