Class: Async::Task

Inherits:
Node
  • Object
show all
Defined in:
lib/async/task.rb

Overview

Encapsulates the state of a running task and it’s result.

“‘mermaid stateDiagram-v2

*

–> Initialized

Initialized –> Running : Run

Running –> Completed : Return Value Running –> Failed : Exception

Completed –> [*] Failed –> [*]

Running –> Stopped : Stop Stopped –> [*] Completed –> Stopped : Stop Failed –> Stopped : Stop Initialized –> Stopped : Stop “‘

Instance Attribute Summary collapse

Attributes inherited from Node

#annotation, #children, #head, #parent, #tail

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Node

#The parent node.=, #annotate, #children?, #consume, #description, #print_hierarchy, #root, #terminate, #transient?, #traverse

Constructor Details

#initialize(parent = Task.current?, finished: nil, **options, &block) ⇒ Task

Create a new task.



70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/async/task.rb', line 70

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

Instance Attribute Details

#fiberObject (readonly)



113
114
115
# File 'lib/async/task.rb', line 113

def fiber
  @fiber
end

#resultObject (readonly)

Access the result of the task without waiting. May be nil if the task is not completed. Does not raise exceptions.



199
200
201
# File 'lib/async/task.rb', line 199

def result
  @result
end

#statusObject (readonly)



150
151
152
# File 'lib/async/task.rb', line 150

def status
  @status
end

Class Method Details

.currentObject

Lookup the Async::Task for the current fiber. Raise ‘RuntimeError` if none is available. @raises If task was not #set! for the current fiber.



236
237
238
# File 'lib/async/task.rb', line 236

def self.current
	Thread.current[:async_task] or raise RuntimeError, "No async task available!"
end

.current?Boolean

Check if there is a task defined for the current fiber.

Returns:

  • (Boolean)


242
243
244
# File 'lib/async/task.rb', line 242

def self.current?
	Thread.current[:async_task]
end

.yieldObject

Deprecated.

With no replacement.



63
64
65
# File 'lib/async/task.rb', line 63

def self.yield
	Fiber.scheduler.transfer
end

Instance Method Details

#alive?Boolean

Whether the internal fiber is alive, i.e. it

Returns:

  • (Boolean)


116
117
118
# File 'lib/async/task.rb', line 116

def alive?
	@fiber&.alive?
end

#async(*arguments, **options, &block) ⇒ Object

Run an asynchronous task as a child of the current task.



166
167
168
169
170
171
172
173
174
# File 'lib/async/task.rb', line 166

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

#backtrace(*arguments) ⇒ Object



89
90
91
# File 'lib/async/task.rb', line 89

def backtrace(*arguments)
	@fiber&.backtrace(*arguments)
end

#completed?Boolean Also known as: complete?

The task has completed execution and generated a result.

Returns:

  • (Boolean)


143
144
145
# File 'lib/async/task.rb', line 143

def completed?
	@status == :completed
end

#current?Boolean

Returns:

  • (Boolean)


246
247
248
# File 'lib/async/task.rb', line 246

def current?
	self.equal?(Thread.current[:async_task])
end

#failed?Boolean

Returns:

  • (Boolean)


133
134
135
# File 'lib/async/task.rb', line 133

def failed?
	@status == :failed
end

#finished?Boolean

Whether we can remove this node from the reactor graph.

Returns:

  • (Boolean)


122
123
124
125
# File 'lib/async/task.rb', line 122

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

#reactorObject



85
86
87
# File 'lib/async/task.rb', line 85

def reactor
	self.root
end

#run(*arguments) ⇒ Object

Begin the execution of the task.



153
154
155
156
157
158
159
160
161
162
163
# File 'lib/async/task.rb', line 153

def run(*arguments)
	if @status == :initialized
		@status = :running
		
		schedule do
			@block.call(self, *arguments)
		end
	else
		raise RuntimeError, "Task already running!"
	end
end

#running?Boolean

Whether the task is running.

Returns:

  • (Boolean)


129
130
131
# File 'lib/async/task.rb', line 129

def running?
	@status == :running
end

#sleep(duration = nil) ⇒ Object

Deprecated.

Prefer Kernel#sleep except when compatibility with ‘stable-v1` is required.



98
99
100
# File 'lib/async/task.rb', line 98

def sleep(duration = nil)
	super
end

#stop(later = false) ⇒ Object

Stop the task and all of its children.



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/async/task.rb', line 202

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

#stopped?Boolean

The task has been stopped

Returns:

  • (Boolean)


138
139
140
# File 'lib/async/task.rb', line 138

def stopped?
	@status == :stopped
end

#to_sObject



93
94
95
# File 'lib/async/task.rb', line 93

def to_s
	"\#<#{self.description} (#{@status})>"
end

#waitObject

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).



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/async/task.rb', line 182

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

#with_timeout(duration, exception = TimeoutError, message = "execution expired", &block) ⇒ Object

Execute the given block of code, raising the specified exception if it exceeds the given duration during a non-blocking operation.



103
104
105
# File 'lib/async/task.rb', line 103

def with_timeout(duration, exception = TimeoutError, message = "execution expired", &block)
	Fiber.scheduler.with_timeout(duration, exception, message, &block)
end

#yieldObject

Yield back to the reactor and allow other fibers to execute.



108
109
110
# File 'lib/async/task.rb', line 108

def yield
	Fiber.scheduler.yield
end