Class: RBlock::Ticker
- Inherits:
-
Object
- Object
- RBlock::Ticker
- Defined in:
- lib/rblocks/ticker.rb
Overview
RBlock::Ticker is a simple Go inspired ticker. Usage ticker = RBlock::Ticker.new(0.5) 10.times do
ticker.wait # blocks for 1/2s
# do a thing every 1/2s
end
Defined Under Namespace
Classes: ErrorTerminated
Constant Summary collapse
- NAME =
"r block ticker"
Instance Method Summary collapse
-
#initialize(interval) ⇒ Ticker
constructor
Constructs and starts a ticker.
-
#stop! ⇒ Object
Stops the ticker.
-
#wait ⇒ Object
Blocks until ractor yields and than yields and returns.
Constructor Details
#initialize(interval) ⇒ Ticker
Constructs and starts a ticker
20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/rblocks/ticker.rb', line 20 def initialize(interval) @stop_ractor = Ractor.new { loop { Ractor.yield(Ractor.recv, move: true) } } @ractor = Ractor.new(interval, @stop_ractor, name: NAME) do |i, stop| loop do r, = Ractor.select(stop, send(nil)) break if r == stop sleep(i) Ractor.yield(Time.now) end end end |
Instance Method Details
#stop! ⇒ Object
Stops the ticker. Calls to #wait
44 45 46 |
# File 'lib/rblocks/ticker.rb', line 44 def stop! @stop_ractor.send(:stop) and loop { break unless wait } end |
#wait ⇒ Object
Blocks until ractor yields and than yields and returns
35 36 37 38 39 40 41 |
# File 'lib/rblocks/ticker.rb', line 35 def wait t = @ractor.take yield(self) if block_given? t rescue Ractor::ClosedError raise ErrorTerminated, "ticker stopped" end |