Module: RubyTimeoutSafe

Defined in:
lib/ruby_timeout_safe.rb,
lib/ruby_timeout_safe/version.rb

Overview

A safe timeout implementation for Ruby using monotonic time.

Constant Summary collapse

VERSION =
'1.0.1'

Class Method Summary collapse

Class Method Details

.timeout(seconds = nil) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/ruby_timeout_safe.rb', line 8

def self.timeout(seconds = nil)
  return yield if seconds.nil? || seconds.zero?

  raise ArgumentError, 'timeout value must be at least 0.1 second' if seconds < 0.1

  current_thread = Thread.current

  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  s_thread = Thread.new do
    loop do
      elapsed_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time
      break if elapsed_time >= seconds

      sleep(0.05) # Sleep briefly to prevent busy-waiting
    end
    current_thread.raise Timeout::Error, 'execution expired'
  end

  yield
ensure
  s_thread.kill if s_thread&.alive?
end