class RuneRb::System::Types::Task

A Task object encapsulates a Fiber that will execute code, then transfer execution context to a target Fiber.

Attributes

id[R]

@!attribute [r] id @return [Integer, Symbol] the Task ID.

priority[R]

@!attribute [r] priority @return [Symbol] the Task priority.

target[R]

@!attribute [r] target @return [Fiber] the target Fiber.

worker[R]

@!attribute [r] worker @return [Fiber] the Fiber that will execute the Task.

Public Class Methods

new(params = {}) { |assets| ... } click to toggle source

Constructs a new Task object. @param params [Hash] Initial parameters for the Task. @param _ [Proc] parameters passed to the block operations

# File deployment/app/system/types/task.rb, line 26
def initialize(params = {}, &_)
  @id = params[:id] || Druuid.gen
  @assets = params[:assets] || []
  @priority = params[:priority] || :LOW
  @worker = Fiber.new do |assets|
    loop do
      result = yield(assets)
    rescue StandardError => e
      err 'An error occurred while processing task!', e, e.message, e.backtrace&.join("\n")
      break
    ensure
      break if @completed

      @target ? @target.transfer(result) : Fiber.yield(result)
    end
  end
  start if params[:autorun]
end

Public Instance Methods

<=>(other) click to toggle source

Mutual comparison operator. Used to sort the Task by it's priority. @param other [Task] the compared Task

# File deployment/app/system/types/task.rb, line 72
def <=>(other)
  RuneRb::System::TASK_PRIORITIES[@priority] <=> RuneRb::System::TASK_PRIORITIES[other.priority]
end
inspect() click to toggle source
# File deployment/app/system/types/task.rb, line 66
def inspect
  "[id]: #{@id}\t||\t[Priority]: #{@priority}"
end
start() click to toggle source

Calls <@worker#resume> causing it to process its work.

# File deployment/app/system/types/task.rb, line 46
def start
  @worker.resume(@assets)
end
stop() click to toggle source

Sets the value of <@completed> to true, preventing further execution of the <@worker>.

# File deployment/app/system/types/task.rb, line 51
def stop
  @completed = true
  # We do this to ensure the loop completes
  start
end
target_to(fiber) click to toggle source

Update the <@target> Fiber to the passed object. @param fiber [Fiber] the new target Fiber. @todo create a InvalidTarget error to properly handle scenarios where a Fiber isn't supplied to this function.

# File deployment/app/system/types/task.rb, line 60
def target_to(fiber)
  raise "Invalid target; must be a Fiber! Received: #{fiber.class}" unless fiber.is_a?(Fiber)

  @target = fiber
end