1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 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
|
require 'hitimes'
module Timers
# An exclusive, monotonic timeout class.
class Wait
def self.for(duration, &block)
if duration
timeout = self.new(duration)
timeout.while_time_remaining(&block)
else
while true
yield(nil)
end
end
end
def initialize(duration)
@duration = duration
@remaining = true
end
attr :duration
attr :remaining
# Yields while time remains for work to be done:
def while_time_remaining(&block)
@interval = Hitimes::Interval.new
@interval.start
while time_remaining?
yield @remaining
end
ensure
@interval.stop
@interval = nil
end
private
def time_remaining?
@remaining = (@duration - @interval.duration)
return @remaining > 0
end
end
end
|