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.



4
5
6
7
# File 'lib/safe_timeout/spawner.rb', line 4

def initialize(options={})
  @expiration = Time.now.to_f + options.fetch(:timeout)
  @on_timeout = options.fetch(:on_timeout)
end

Instance Method Details

#spawn_interrupterObject



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

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(bin, $$.to_s, @expiration.to_s)
  Process.detach(@child_pid)
end

#start(&block) ⇒ Object



9
10
11
12
13
14
15
16
# File 'lib/safe_timeout/spawner.rb', line 9

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

#stopObject



18
19
20
21
# File 'lib/safe_timeout/spawner.rb', line 18

def stop
  # Tell that child to stop interrupting!
  SafeTimeout.send_signal('HUP', @child_pid)
end