Class: RBlock::Timer

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

Overview

RBlock::Timer is a simple Go inspired timer. Usage timer = RBlock::Timer.new(10) timer.wait do

# ... someting once the time is up

end

Constant Summary collapse

NAME =
"r block timer"

Instance Method Summary collapse

Constructor Details

#initialize(duration) ⇒ Timer

Constructs and starts a timer

Parameters:

  • duration (Numeric)

    duration in seconds



17
18
19
20
21
22
23
# File 'lib/rblocks/timer.rb', line 17

def initialize(duration)
  @ractor = Ractor.new(duration, name: NAME) do |time|
    sleep(time)

    Ractor.yield(:done)
  end
end

Instance Method Details

#wait {|_self| ... } ⇒ Object

Blocks until the timer is done. Yields self to block if one is given

Yields:

  • (_self)

Yield Parameters:

  • _self (RBlock::Timer)

    the object that the method was called on



28
29
30
31
32
# File 'lib/rblocks/timer.rb', line 28

def wait
  done = @ractor.take
  yield(self) if block_given?
  done
end