From b3b55bbe4086ce28a7d9528b544964236795e526 Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Thu, 13 Jun 2024 13:51:58 +0900 Subject: [PATCH] `Timers#after` converts argument to float. (#109) --- lib/io/event/selector/select.rb | 1 - lib/io/event/timers.rb | 7 ++++--- test/io/event/timers.rb | 30 ++++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/lib/io/event/selector/select.rb b/lib/io/event/selector/select.rb index eb5d0281..588b4e05 100644 --- a/lib/io/event/selector/select.rb +++ b/lib/io/event/selector/select.rb @@ -421,7 +421,6 @@ def select(duration = nil) error = nil if duration - duration = duration/1.0 if duration > 0 start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) end diff --git a/lib/io/event/timers.rb b/lib/io/event/timers.rb index 4c2ca2f5..bae5a379 100644 --- a/lib/io/event/timers.rb +++ b/lib/io/event/timers.rb @@ -50,18 +50,19 @@ def size end # Schedule a block to be called at a specific time in the future. - # @parameter time [Time] The time at which the block should be called, relative to {#now}. + # @parameter time [Float] The time at which the block should be called, relative to {#now}. def schedule(time, block) handle = Handle.new(time, block) + @scheduled << handle return handle end # Schedule a block to be called after a specific time offset, relative to the current time as returned by {#now}. - # @parameter offset [Time] The time offset from the current time at which the block should be called. + # @parameter offset [#to_f] The time offset from the current time at which the block should be called. def after(offset, &block) - schedule(self.now + offset, block) + schedule(self.now + offset.to_f, block) end def wait_interval(now = self.now) diff --git a/test/io/event/timers.rb b/test/io/event/timers.rb index 9a4d807f..04fc52ee 100644 --- a/test/io/event/timers.rb +++ b/test/io/event/timers.rb @@ -5,6 +5,16 @@ require 'io/event/timers' +class FloatWrapper + def initialize(value) + @value = value + end + + def to_f + @value + end +end + describe IO::Event::Timers do let(:timers) {subject.new} @@ -67,6 +77,26 @@ expect(timers.size).to be == 0 end + with '#schedule' do + it "raises an error if given an invalid time" do + expect do + timers.after(Object.new) {} + end.to raise_exception(NoMethodError, message: be =~ /to_f/) + end + + it "converts the offset to a float" do + fired = false + + timers.after(FloatWrapper.new(0.1)) do + fired = true + end + + timers.fire(timers.now + 0.15) + + expect(fired).to be == true + end + end + with '#wait_interval' do it "should return nil if no timers are scheduled" do expect(timers.wait_interval).to be_nil