class

Context

Inherits Reference < Object

Go-style cooperative cancellation, deadlines, and blocking helpers for Crystal.

Constants

DEADLINE_EXCEEDED = "context deadline exceeded"
DEFAULT_REASON = "context cancelled"

Constructors

background

Returns a root context that is never canceled and has no deadline.

Source
with_cancel(parent : Context) : Context

Creates a cancelable child context.

Source
with_cancel

Creates a cancelable context with Context.background as its parent.

Source
with_deadline(parent : Context, deadline : Time) : Context

Creates a child context canceled when deadline arrives or its parent is canceled.

Source
with_deadline(deadline : Time) : Context

Creates a context canceled at deadline with Context.background as parent.

Source
with_timeout(parent : Context, timeout : Time::Span) : Context

Creates a child context canceled when timeout expires or its parent is canceled.

Source
with_timeout(timeout : Time::Span) : Context

Creates a context canceled after timeout with Context.background as parent.

Source

Class methods

receive(ctx : Context, channel : Channel(T)) : T forall T

Receives from channel or raises when ctx is canceled.

Source
send(ctx : Context, channel : Channel(T), value : T) : Nil forall T

Sends value to channel or raises when ctx is canceled.

Source
sleep(ctx : Context, duration : Time::Span) : Nil

Sleeps until duration elapses or ctx is canceled.

Source
spawn(ctx : Context, &block : Context -> ) : Fiber

Spawns a fiber with a cancelable child context.

Source

Instance methods

cancel(reason : String | Nil = nil) : Bool

Cancels this context and its children once.

Source
cancelled?

Returns true when this context has been canceled or its deadline expired.

Source
checkpoint!

Raises Context::Cancelled if this context is canceled.

Source
deadline

Returns the effective deadline for this context as a monotonic instant, if any.

Source
done

Returns a channel that is closed when this context is canceled.

Use it to compose your own select. Receive-only: never send to or close the returned channel. A context with no cancellation source returns a fresh channel that never closes.

Source
reason

Returns the reason supplied when this context was first canceled.

Source
value(key : Symbol, type : T.class) : T | Nil forall T

Returns a symbol-keyed request-scoped value, if present.

Source
value(key : Key(T)) : T | Nil forall T

Returns a typed request-scoped value, if present.

Source
with_value(key : Key(T), value : T) : Context forall T

Returns a copy of this context with a typed request-scoped value.

Source
with_value(key : Symbol, value : T) : Context forall T

Returns a copy of this context with a symbol-keyed request-scoped value.

Source

Nested types