Class: SafeTimeout::Spawner
- Inherits:
-
Object
- Object
- SafeTimeout::Spawner
- Defined in:
- lib/safe_timeout/spawner.rb
Instance Method Summary collapse
-
#initialize(options = {}) ⇒ Spawner
constructor
A new instance of Spawner.
- #spawn_interrupter ⇒ Object
- #start ⇒ Object
- #stop ⇒ Object
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( = {}) @expiration = Time.now.to_f + .fetch(:timeout) @on_timeout = lambda do |*args| @timed_out = true .fetch(:on_timeout).call(*args) end @timed_out = false end |
Instance Method Details
#spawn_interrupter ⇒ Object
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 |
#start ⇒ Object
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 |
#stop ⇒ Object
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 |