Class: Forked::WithGracefulShutdown

Inherits:
Object
  • Object
show all
Defined in:
lib/forked/with_graceful_shutdown.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger:) ⇒ WithGracefulShutdown

Returns a new instance of WithGracefulShutdown.



36
37
38
39
# File 'lib/forked/with_graceful_shutdown.rb', line 36

def initialize(logger:)
  @logger = logger
  @shutdown = false
end

Class Method Details

.loop(sleep_seconds: 1, &block) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/forked/with_graceful_shutdown.rb', line 18

def self.loop(sleep_seconds: 1, &block)
  run do |ready_to_stop|
    Kernel.loop do
      ready_to_stop.call
      yield ready_to_stop
      ready_to_stop.call
      sleep_seconds.times do
        ready_to_stop.call
        sleep(1)
      end
    end
  end
end

.run(logger: Logger.new(STDOUT), &block) ⇒ Object



32
33
34
# File 'lib/forked/with_graceful_shutdown.rb', line 32

def self.run(logger: Logger.new(STDOUT), &block)
  new(logger: logger).run(&block)
end

Instance Method Details

#runObject



41
42
43
44
45
46
47
48
# File 'lib/forked/with_graceful_shutdown.rb', line 41

def run
  trap_shutdown_signals do
    catch(:stop) do
      ready_to_stop = -> { stop_if_necessary }
      yield ready_to_stop
    end
  end
end

#shutdownObject



57
58
59
# File 'lib/forked/with_graceful_shutdown.rb', line 57

def shutdown
  @shutdown = true
end

#stop_if_necessaryObject



50
51
52
53
54
55
# File 'lib/forked/with_graceful_shutdown.rb', line 50

def stop_if_necessary
  if @shutdown
    @logger.info("Shutting down")
    throw :stop
  end
end