Class: SafeTimeout::Spawner

Inherits:
Object
  • Object
show all
Defined in:
lib/safe_timeout/spawner.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Spawner

Returns a new instance of Spawner.



5
6
7
8
9
10
11
12
# File 'lib/safe_timeout/spawner.rb', line 5

def initialize(options = {})
  @expiration = Time.now.to_f + options.fetch(:timeout)
  @on_timeout = lambda do |*args|
    @timed_out = true
    options.fetch(:on_timeout).call(*args)
  end
  @timed_out = false
end

Instance Method Details

#spawn_interrupterObject



29
30
31
32
33
34
35
# File 'lib/safe_timeout/spawner.rb', line 29

def spawn_interrupter
  # Create a light-weight child process to notify this process if it is
  # taking too long
  bin = Gem.bin_path('safe_timeout', 'safe_timeout')
  @child_pid = Process.spawn({ 'COVERAGE' => defined?(SimpleCov) }, bin, @expiration.to_s)
  Process.detach(@child_pid)
end

#startObject



14
15
16
17
18
19
20
21
# File 'lib/safe_timeout/spawner.rb', line 14

def start
  original = Signal.trap('TRAP', &@on_timeout) || 'DEFAULT'
  spawn_interrupter
  yield
ensure
  Signal.trap('TRAP', original)
  stop
end

#stopObject



23
24
25
26
27
# File 'lib/safe_timeout/spawner.rb', line 23

def stop
  # Tell that child to stop interrupting!
  SafeTimeout.send_signal('HUP', @child_pid) unless @timed_out
  Process.wait(@child_pid) rescue nil
end