Class: RGossip2::Timer

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

Overview

class Timer 一定時間でNodeを削除するためのクラス 唯一、Contextを参照しない

-------- --------- | Node |<>—–+| Timer | -------- ---------

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(timeout, &block) ⇒ Timer

Returns a new instance of Timer.



16
17
18
19
# File 'lib/rgossip2/timer.rb', line 16

def initialize(timeout, &block)
  @timeout = timeout
  @block = block
end

Instance Attribute Details

#timeoutObject

Returns the value of attribute timeout.



14
15
16
# File 'lib/rgossip2/timer.rb', line 14

def timeout
  @timeout
end

Instance Method Details

#resetObject

カウントダウンをリセットする



51
52
53
54
55
56
57
58
# File 'lib/rgossip2/timer.rb', line 51

def reset
  if alive?
    @start_time = Time.now
    @thread.run # 停止中のスレッドを強制起動してスリープ時間を更新
  end
rescue ThreadError
  # @thread.runで発生する可能性があるが無視
end

#startObject



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
47
48
# File 'lib/rgossip2/timer.rb', line 21

def start
  # 既存のスレッドは破棄
  @thread.kill if alive?
  @start_time = Time.now

  # スタート時点の「開始時刻」を引数に渡す
  @thread = Thread.start(@start_time) {|start_time|
    loop do
      # タイムアウトするまでスリープ
      sleep @timeout

      if @start_time == start_time
        # 開始時刻が変わっていない=リセットされない場合
        # 破棄の処理を呼び出してループを抜ける(=スレッドの終了)
        @block.call
        break
      elsif @start_time.nil?
        # Timerがストップされていた場合
        # 何もしないでループを抜ける(=スレッドの終了)
        break
      else
        # 開始時刻が更新された場合=リセットされた場合
        # start_timeを更新してループを継続(=スレッドの継続)
        start_time = @start_time
      end
    end # loop
  } # Thread.start
end

#stopObject

カウントダウンを停止する



61
62
63
64
65
66
67
68
# File 'lib/rgossip2/timer.rb', line 61

def stop
  if alive?
    @start_time = nil
    @thread.run # 停止中のスレッドを強制起動して終了させる
  end
rescue ThreadError
  # @thread.runで発生する可能性があるが無視
end