Method: Fiber.schedule

Defined in:
cont.c

.schedule {|*args| ... } ⇒ Object

The method is expected to immediately run the provided block of code in a separate non-blocking fiber.

puts "Go to sleep!"

Fiber.set_scheduler(MyScheduler.new)

Fiber.schedule do
  puts "Going to sleep"
  sleep(1)
  puts "I slept well"
end

puts "Wakey-wakey, sleepyhead"

Assuming MyScheduler is properly implemented, this program will produce:

Go to sleep!
Going to sleep
Wakey-wakey, sleepyhead
...1 sec pause here...
I slept well

…e.g. on the first blocking operation inside the Fiber (sleep(1)), the control is yielded to the outside code (main fiber), and at the end of that execution, the scheduler takes care of properly resuming all the blocked fibers.

Note that the behavior described above is how the method is expected to behave, actual behavior is up to the current scheduler’s implementation of Fiber::Scheduler#fiber method. Ruby doesn’t enforce this method to behave in any particular way.

If the scheduler is not set, the method raises RuntimeError (No scheduler is available!).

Yields:

  • (*args)


2369
2370
2371
2372
2373
# File 'cont.c', line 2369

static VALUE
rb_fiber_s_schedule(int argc, VALUE *argv, VALUE obj)
{
    return rb_fiber_s_schedule_kw(argc, argv, rb_keyword_given_p());
}