Class: PSI::Monitor

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

Overview

Multiplexes PSI triggers on one background thread.

Instance Method Summary collapse

Constructor Details

#initializeMonitor

Returns a new instance of Monitor.



6
7
8
9
10
# File 'lib/psi/monitor.rb', line 6

def initialize
  @entries = []
  @wake_reader, @wake_writer = IO.pipe
  @error_handler = ->(error) { warn "PSI monitor: #{error.message}" }
end

Instance Method Details

#on(resource, **options, &callback) ⇒ Object

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
# File 'lib/psi/monitor.rb', line 12

def on(resource, **options, &callback)
  raise ArgumentError, "a callback is required" unless callback
  raise Error, "monitor is already running" if @thread
  raise Error, "monitor is stopped" if stopped?

  @entries << [Trigger.new(resource, **options), callback]
  self
end

#on_error(&handler) ⇒ Object

Raises:

  • (ArgumentError)


21
22
23
24
25
26
# File 'lib/psi/monitor.rb', line 21

def on_error(&handler)
  raise ArgumentError, "an error handler is required" unless handler

  @error_handler = handler
  self
end

#startObject

Raises:



28
29
30
31
32
33
34
# File 'lib/psi/monitor.rb', line 28

def start
  raise Error, "monitor is stopped" if stopped?
  return self if @thread&.alive?

  @thread = Thread.new { run }
  self
end

#stopMonitor

Stops monitoring, wakes the select call, and closes every trigger.

Returns:



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/psi/monitor.rb', line 38

def stop
  return self if stopped?

  @stop = true
  @wake_writer.write_nonblock(".") if @thread&.alive?
  @thread.join if @thread && @thread != Thread.current
  close unless @thread
  self
rescue Errno::EPIPE, IOError
  self
end