class Task
Encapsulates the state of a running task and it's result.
Signature
- public
Since
stable-v1
.
Definitions
def self.yield
- deprecated
Signature
- deprecated
With no replacement.
Implementation
def self.yield
Fiber.scheduler.transfer
end
def yield
Yield back to the reactor and allow other fibers to execute.
Implementation
def yield
Fiber.scheduler.yield
end
def initialize(parent = Task.current?, finished: nil, **options, &block)
Create a new task.
Signature
-
parameter
reactor
Reactor
the reactor this task will run within.
-
parameter
parent
Task
the parent task.
Implementation
def initialize(parent = Task.current?, finished: nil, **options, &block)
super(parent, **options)
# These instance variables are critical to the state of the task.
# In the initialized state, the @block should be set, but the @fiber should be nil.
# In the running state, the @fiber should be set.
# In a finished state, the @block should be nil, and the @fiber should be nil.
@block = block
@fiber = nil
@status = :initialized
@result = nil
@finished = finished
end
def sleep(duration = nil)
- deprecated
Signature
- deprecated
Prefer
Kernel#sleep
except when compatibility withstable-v1
is required.
Implementation
def sleep(duration = nil)
super
end
def with_timeout(duration, exception = TimeoutError, message = "execution expired", &block)
Execute the given block of code, raising the specified exception if it exceeds the given duration during a non-blocking operation.
Implementation
def with_timeout(duration, exception = TimeoutError, message = "execution expired", &block)
Fiber.scheduler.with_timeout(duration, exception, message, &block)
end
attr :fiber
def alive?
Whether the internal fiber is alive, i.e. it
Implementation
def alive?
@fiber&.alive?
end
def finished?
Whether we can remove this node from the reactor graph.
Signature
-
returns
Boolean
Implementation
def finished?
# If the block is nil and the fiber is nil, it means the task has finished execution. This becomes true after `finish!` is called.
super && @block.nil? && @fiber.nil?
end
def running?
Whether the task is running.
Signature
-
returns
Boolean
Implementation
def running?
@status == :running
end
def stopped?
The task has been stopped
Implementation
def stopped?
@status == :stopped
end
def completed?
The task has completed execution and generated a result.
Implementation
def completed?
@status == :completed
end
attr :status
def run(*arguments)
Begin the execution of the task.
Implementation
def run(*arguments)
if @status == :initialized
@status = :running
schedule do
@block.call(self, *arguments)
end
else
raise RuntimeError, "Task already running!"
end
end
def async(*arguments, **options, &block)
Run an asynchronous task as a child of the current task.
Implementation
def async(*arguments, **options, &block)
raise "Cannot create child task within a task that has finished execution!" if self.finished?
task = Task.new(self, **options, &block)
task.run(*arguments)
return task
end
def wait
Retrieve the current result of the task. Will cause the caller to wait until result is available. If the result was an exception, raise that exception.
Conceptually speaking, waiting on a task should return a result, and if it throws an exception, this is certainly an exceptional case that should represent a failure in your program, not an expected outcome. In other words, you should not design your programs to expect exceptions from #wait
as a normal flow control, and prefer to catch known exceptions within the task itself and return a result that captures the intention of the failure, e.g. a TimeoutError
might simply return nil
or false
to indicate that the operation did not generate a valid result (as a timeout was an expected outcome of the internal operation in this case).
Signature
-
raises
RuntimeError
If the task's fiber is the current fiber.
-
returns
Object
The final expression/result of the task's block.
Implementation
def wait
raise "Cannot wait on own fiber!" if Fiber.current.equal?(@fiber)
# `finish!` will set both of these to nil before signaling the condition:
if @block || @fiber
@finished ||= Condition.new
@finished.wait
end
if @result.is_a?(Exception)
raise @result
else
return @result
end
end
attr :result
Access the result of the task without waiting. May be nil if the task is not completed. Does not raise exceptions.
def stop(later = false)
Stop the task and all of its children.
Implementation
def stop(later = false)
if self.stopped?
# If we already stopped this task... don't try to stop it again:
return
end
# If the fiber is alive, we need to stop it:
if @fiber&.alive?
if self.current?
if later
# If the fiber is the current fiber and we want to stop it later, schedule it:
Fiber.scheduler.push(Stop::Later.new(self))
else
# Otherwise, raise the exception directly:
raise Stop, "Stopping current task!"
end
else
# If the fiber is not curent, we can raise the exception directly:
begin
Fiber.scheduler.raise(@fiber, Stop)
rescue FiberError
# In some cases, this can cause a FiberError (it might be resumed already), so we schedule it to be stopped later:
Fiber.scheduler.push(Stop::Later.new(self))
end
end
else
# We are not running, but children might be, so transition directly into stopped state:
stop!
end
end
def self.current
Lookup the class Async::Task
for the current fiber. Raise RuntimeError
if none is available.
Signature
-
returns
Task
Implementation
def self.current
Thread.current[:async_task] or raise RuntimeError, "No async task available!"
end
def self.current?
Check if there is a task defined for the current fiber.
Signature
-
returns
Task | Nil
Implementation
def self.current?
Thread.current[:async_task]
end
def finish!
Finish the current task, moving any children to the parent.
Implementation
def finish!
# Don't hold references to the fiber or block after the task has finished:
@fiber = nil
@block = nil # If some how we went directly from initialized to finished.
# Attempt to remove this node from the task tree.
consume
# If this task was being used as a future, signal completion here:
if @finished
@finished.signal(self)
@finished = nil
end
end
def completed!(result)
State transition into the completed state.
Implementation
def completed!(result)
@result = result
@status = :completed
end
def failed!(exception = false, propagate = true)
This is a very tricky aspect of tasks to get right. I've modelled it after Thread
but it's slightly different in that the exception can propagate back up through the reactor. If the user writes code which raises an exception, that exception should always be visible, i.e. cause a failure. If it's not visible, such code fails silently and can be very difficult to debug.
Implementation
def failed!(exception = false, propagate = true)
@result = exception
@status = :failed
if exception
if propagate
raise exception
elsif @finished.nil?
# If no one has called wait, we log this as a warning:
Console.logger.warn(self, "Task may have ended with unhandled exception.", exception)
else
Console.logger.debug(self, exception)
end
end
end
def set!
Set the current fiber's :async_task
to this task.
Implementation
def set!
# This is actually fiber-local:
Thread.current[:async_task] = self
end