AsyncSourceAsyncDeadline

class Deadline

Represents a deadline timeout with decrementing remaining time. Includes an efficient representation for zero (non-blocking) timeouts.

Signature

public

Since Async v2.31.

Nested

Definitions

def self.start(timeout)

Create a deadline for the given timeout.

Signature

parameter timeout Numeric | Nil

The timeout duration, or nil for no timeout.

returns Deadline | Nil

A deadline instance, Zero singleton, or nil.

Implementation

def self.start(timeout)
	if timeout.nil?
		nil
	elsif timeout <= 0
		Zero
	else
		self.new(timeout)
	end
end

def initialize(remaining)

Create a new deadline with the specified remaining time.

Signature

parameter remaining Numeric

The initial remaining time.

Implementation

def initialize(remaining)
	@remaining = remaining
	@start = Clock.now
end

def remaining

Get the remaining time, updating internal state. Each call to this method advances the internal clock and reduces the remaining time by the elapsed duration since the last call.

Signature

returns Numeric

The remaining time (may be negative if expired).

Implementation

def remaining
	now = Clock.now
	delta = now - @start
	@start = now
	
	@remaining -= delta
	
	return @remaining
end

def expired?

Check if the deadline has expired.

Signature

returns Boolean

True if no time remains.

Implementation

def expired?
	self.remaining <= 0
end

Discussion