Class: Dizby::TimedCollection

Inherits:
Object
  • Object
show all
Defined in:
lib/dizby/utility/timed_collection.rb

Instance Method Summary collapse

Constructor Details

#initialize(timeout, step = timeout) ⇒ TimedCollection

Returns a new instance of TimedCollection.


11
12
13
14
15
16
# File 'lib/dizby/utility/timed_collection.rb', line 11

def initialize(timeout, step = timeout)
  @timeout = timeout
  @step = [timeout, step].min # don't allow a larger step than timeout
  @states = Dizby.monitor({})
  @updater = Thread.start { update }
end

Instance Method Details

#add(id)


24
25
26
# File 'lib/dizby/utility/timed_collection.rb', line 24

def add(id)
  @states.synchronize { @states[id] = TimedState.new(@timeout) }
end

#revive(id)


18
19
20
21
22
# File 'lib/dizby/utility/timed_collection.rb', line 18

def revive(id)
  @states.synchronize { @states.fetch(id).revive }
rescue KeyError
  raise InvalidIdentifier, 'identifier timed out or did not exist'
end

#update (private)


30
31
32
33
34
35
36
37
38
39
# File 'lib/dizby/utility/timed_collection.rb', line 30

def update
  loop do
    sleep(@step)

    @states.synchronize do
      @states.each_value(&:update)
      @states.keep_if { |_, state| state.alive? }
    end
  end
end