Skip to content

Commit 86ba825

Browse files
code's refactored in favor of run_after method instead of run_every
1 parent d0a5f4b commit 86ba825

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

lib/rage/fiber_scheduler.rb

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,12 @@
44

55
class Rage::FiberScheduler
66
MAX_READ = 65536
7-
TIMEOUT_WORKER_INTERVAL = 100 # miliseconds
87

98
def initialize
109
@root_fiber = Fiber.current
1110
@dns_cache = {}
1211

1312
@fiber_timeouts = Hash.new { |h, k| h[k] = {} }
14-
15-
start_timeout_worker
1613
end
1714

1815
def io_wait(io, events, timeout = nil)
@@ -80,6 +77,8 @@ def timeout_after(duration, exception_class = Timeout::Error, *exception_argumen
8077
exception_arguments: exception_arguments
8178
}
8279

80+
schedule_timeout_check
81+
8382
begin
8483
block.call
8584
ensure
@@ -156,9 +155,25 @@ def close
156155

157156
private
158157

159-
def start_timeout_worker
160-
::Iodine.run_every(Rage::FiberScheduler::TIMEOUT_WORKER_INTERVAL) do
158+
def schedule_timeout_check
159+
return if @fiber_timeouts.empty?
160+
161+
closest_timeout = nil
162+
@fiber_timeouts.each_value do |timeouts|
163+
timeouts.each_key do |timeout|
164+
closest_timeout = timeout if closest_timeout.nil? || timeout < closest_timeout
165+
end
166+
end
167+
168+
return unless closest_timeout
169+
170+
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
171+
delay_ms = ((closest_timeout - now) * 1000).ceil
172+
delay_ms = 0 if delay_ms < 0
173+
174+
::Iodine.run_after(delay_ms) do
161175
check_timeouts
176+
schedule_timeout_check
162177
end
163178
end
164179

0 commit comments

Comments
 (0)