Class: LittleGhost::Support::TaskRunner

Inherits:
Object
  • Object
show all
Defined in:
lib/little_ghost/support/task_runner.rb

Overview

TaskRunner starts framework work on threads or scheduled fibers. :auto uses a fiber only when the caller is already in one. LittleGhost never installs or controls the scheduler.

Constant Summary collapse

BACKENDS =

:nodoc:

%i[auto thread fiber].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(backend: :auto) ⇒ TaskRunner

Returns a new instance of TaskRunner.



14
15
16
17
18
19
20
# File 'lib/little_ghost/support/task_runner.rb', line 14

def initialize(backend: :auto)
  unless BACKENDS.include?(backend)
    raise ArgumentError, "backend must be :auto, :thread, or :fiber"
  end

  @backend = backend
end

Instance Attribute Details

#backendObject (readonly)

The configured :auto, :thread, or :fiber policy.



12
13
14
# File 'lib/little_ghost/support/task_runner.rb', line 12

def backend
  @backend
end

Instance Method Details

#spawn(&work) ⇒ Object

Starts a Task and returns it immediately.

Raises:

  • (ArgumentError)


23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/little_ghost/support/task_runner.rb', line 23

def spawn(&work)
  raise ArgumentError, "a task block is required" unless work

  resolved_backend = resolve_backend
  task = build_task(&work)
  worker = if resolved_backend == :fiber
    Fiber.schedule { task.call }
  else
    Thread.new { task.call }
  end
  thread_worker = resolved_backend == :thread
  task.start(worker, terminable: thread_worker, joinable: thread_worker)
end

#try_spawn(&work) ⇒ Object

Starts a Task when capacity is immediately available. The ordinary runner has no shared capacity limit, so it always accepts the task.



39
40
41
# File 'lib/little_ghost/support/task_runner.rb', line 39

def try_spawn(&work)
  spawn(&work)
end

#uses_current_scheduler?Boolean

Indicates that #spawn would use the caller's active Fiber scheduler.

Returns:

  • (Boolean)


44
45
46
# File 'lib/little_ghost/support/task_runner.rb', line 44

def uses_current_scheduler?
  resolve_backend == :fiber
end