Class: SafePoller::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/safe_poller/base.rb

Instance Method Summary collapse

Constructor Details

#initialize(**options, &block) ⇒ Base

Returns a new instance of Base.



5
6
7
8
9
10
11
12
13
14
# File 'lib/safe_poller/base.rb', line 5

def initialize(**options, &block)
  @block = block
  @running = false
  @paused = false
  @thread = nil
  @mutex = Mutex.new
  @pause_cv = ConditionVariable.new
  @interval = options.fetch(:interval, 1.0)
  @until = options.fetch(:until, nil)
end

Instance Method Details

#pauseObject



50
51
52
53
54
55
56
# File 'lib/safe_poller/base.rb', line 50

def pause
  return unless @running

  @mutex.synchronize do
    @paused = true
  end
end

#paused?Boolean

Returns:

  • (Boolean)


71
72
73
# File 'lib/safe_poller/base.rb', line 71

def paused?
  @paused
end

#resumeObject



58
59
60
61
62
63
64
65
# File 'lib/safe_poller/base.rb', line 58

def resume
  return unless @running

  @mutex.synchronize do
    @paused = false
    @pause_cv.signal
  end
end

#running?Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/safe_poller/base.rb', line 67

def running?
  @running
end

#startObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/safe_poller/base.rb', line 16

def start
  return if @running

  @running = true

  @thread = Thread.new do
    loop do
      @mutex.synchronize do
        @pause_cv.wait(@mutex) if @paused
      end

      break unless @running
      break if @until && Time.now >= @until

      @block.call

      sleep @interval
    end
  end
end

#stopObject



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

def stop
  return unless @running

  @mutex.synchronize do
    @running = false
    @paused = false
    @pause_cv.signal
  end

  @thread.join
  @thread = nil
end