Skip to content

Instantly share code, notes, and snippets.

@cristianrasch
Last active March 19, 2019 20:04
Show Gist options
  • Save cristianrasch/8bba7394b4c62b6f2ed55530116dae32 to your computer and use it in GitHub Desktop.
Save cristianrasch/8bba7394b4c62b6f2ed55530116dae32 to your computer and use it in GitHub Desktop.
require "English"
require "logger"
require "pathname"
# kill me with kill -INT PID
script_path = Pathname(__FILE__)
pid_file = script_path.sub_ext(".pid")
pid_file.write(String(Process.pid))
log_file = Pathname(script_path).sub_ext(".log")
logger = Logger.new(log_file, 7, 1024*1024)
logger.level = Logger::DEBUG
logger.debug "PID: #{Process.pid}"
shutdown = false
on_int_or_term_signal = proc {
p "Received shutdown signal"
# signal handler may have already deleted the PIDFILE
pid_file.unlink if pid_file.exist?
if $ERROR_INFO
p "#{$ERROR_INFO} - POS: #{$ERROR_POSITION}"
end
shutdown = true
}
trap("INT", &on_int_or_term_signal)
# trap("TERM", &on_int_or_term_signal)
# at_exit(&on_int_or_term_signal)
workers = 1.upto(4).map { |i|
Thread.new(i) do |j|
loop do
break if shutdown
logger.debug "Thread ##{j} about to go to sleep"
sleep(j)
end
end
}
loop do
sleep 1
if shutdown
workers.each.with_index do |worker, i|
res = begin
worker.join(i + 1)
rescue => err
logger.error err.message
logger.error err.backtrace.join("\n")
true # thread already killed
end
Thread.kill(worker) unless res
end
break
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment