File: wait.rb

package info (click to toggle)
ruby-timers 4.4.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 216 kB
  • sloc: ruby: 973; makefile: 6
file content (54 lines) | stat: -rw-r--r-- 1,036 bytes parent folder | download
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
49
50
51
52
53
54
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2014-2025, by Samuel Williams.
# Copyright, 2014-2016, by Tony Arcieri.
# Copyright, 2015, by Utenmiki.
# Copyright, 2015, by Donovan Keme.

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
				# If there is no "duration" to wait for, we wait forever.
				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