Class: RGossip::Timer

Inherits:
Object
  • Object
show all
Defined in:
lib/rgossip/timer.rb

Instance Method Summary collapse

Constructor Details

#initialize(timeout, &block) ⇒ Timer

Returns a new instance of Timer.



3
4
5
6
7
8
# File 'lib/rgossip/timer.rb', line 3

def initialize(timeout, &block)
  @timeout = timeout
  @block = block
  @mutex = Mutex.new
  @reset = false
end

Instance Method Details

#resetObject



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rgossip/timer.rb', line 31

def reset
  @mutex.synchronize {
    if_is_thread_alive? do
      begin
        @reset = true
        @thread.run
      ensure
        @reset = false
      end
    end
  }
rescue ThreadError
end

#startObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/rgossip/timer.rb', line 10

def start
  @mutex.synchronize {
    if_is_thread_alive? { @thread.kill }
    @reset = false

    @thread = Thread.start {
      loop do
        sleep @timeout

        if @reset
          @reset = false
          retry
        end

        @block.call
        break
      end
    }
  }
end