diff --git a/example-app/README.md b/example-app/README.md index a365c5a..587397c 100644 --- a/example-app/README.md +++ b/example-app/README.md @@ -7,3 +7,12 @@ To run: bundle bundle exec clock ``` + +To test invocation of existing signal handlers, put this code at the very top of exe/clock: + +```ruby +Signal.trap('INT') do + puts "This is a well-behaving INT handler from outside of ruby-clock" + exit +end +``` diff --git a/exe/clock b/exe/clock index 6ca230f..7e55fc5 100755 --- a/exe/clock +++ b/exe/clock @@ -4,6 +4,7 @@ require 'ruby-clock' require "ruby-clock/dsl" RubyClock.detect_and_load_rails_app require 'rufus_monkeypatch' +RubyClock.instance.listen_for_shutdown RubyClock.instance.listen_to_signals RubyClock.instance.prepare_rake RubyClock.instance.schedule.pause diff --git a/lib/ruby-clock.rb b/lib/ruby-clock.rb index d7ea7b1..43af89d 100644 --- a/lib/ruby-clock.rb +++ b/lib/ruby-clock.rb @@ -15,6 +15,7 @@ class RubyClock include RubyClock::AroundActions attr_accessor :on_error, :around_trigger_code_location + attr_accessor :should_shutdown, :old_shutdown_handler def initialize set_up_around_actions @@ -24,6 +25,22 @@ def wait_seconds ENV['RUBY_CLOCK_SHUTDOWN_WAIT_SECONDS']&.to_i || 29 end + def listen_for_shutdown + Thread.new do + loop do + sleep 1 + if should_shutdown + shutdown + if old_shutdown_handler + old_shutdown_handler.call + else + exit + end + end + end + end + end + def shutdown puts "Shutting down ruby-clock. Waiting #{wait_seconds} seconds for jobs to finish..." schedule.shutdown(wait: wait_seconds) @@ -34,12 +51,10 @@ def listen_to_signals signals = %w[INT TERM] signals.each do |signal| old_handler = Signal.trap(signal) do - shutdown if old_handler.respond_to?(:call) - old_handler.call - else - exit + self.old_shutdown_handler = old_handler end + self.should_shutdown = true end end puts "RUBY_CLOCK_SHUTDOWN_WAIT_SECONDS is set to #{wait_seconds}"