Sha256: a29defa59f15ac4c744b71f76b442873248d22c2c9f071cd3a626ee25251f1e2

Contents?: true

Size: 912 Bytes

Versions: 3

Compression:

Stored size: 912 Bytes

Contents

# frozen_string_literal: true
#
# This file is part of the "timers" project and released under the MIT license.
#
# Copyright, 2018, by Samuel Williams. All rights reserved.
#

require_relative "interval"

module Timers
	# An exclusive, monotonic timeout class.
	class Wait
		def self.for(duration, &block)
			if duration
				timeout = new(duration)

				timeout.while_time_remaining(&block)
			else
				loop do
					yield(nil)
				end
			end
		end

		def initialize(duration)
			@duration = duration
			@remaining = true
		end

		attr_reader :duration
		attr_reader :remaining

		# Yields while time remains for work to be done:
		def while_time_remaining
			@interval = Interval.new
			@interval.start

			yield @remaining while time_remaining?
		ensure
			@interval.stop
			@interval = nil
		end

		private

		def time_remaining?
			@remaining = (@duration - @interval.to_f)

			@remaining > 0
		end
	end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
timers-4.3.0 lib/timers/wait.rb
timers-4.2.1 lib/timers/wait.rb
timers-4.2.0 lib/timers/wait.rb