Last active
March 19, 2019 20:04
-
-
Save cristianrasch/8bba7394b4c62b6f2ed55530116dae32 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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