Skip to content

Instantly share code, notes, and snippets.

@ridiculous
Last active January 31, 2017 08:56
Show Gist options
  • Save ridiculous/abf7fed61b1c9d6059e0edf06c511d4a to your computer and use it in GitHub Desktop.
Save ridiculous/abf7fed61b1c9d6059e0edf06c511d4a to your computer and use it in GitHub Desktop.
# @usage Start and stop a ruby process that just logs to a file every couple seconds, but can be interrupted gracefully
#
# ruby script/wb
# kill -INT `cat tmp/pids/wb.pid`
#
require "logger"
require "fileutils"
PID_FILE = File.expand_path("../../tmp/pids/wb.pid", __FILE__)
LOG_FILE = File.expand_path("../../log/wb.log", __FILE__)
module Worker
extend self
def call
logger.info "Hello world"
Thread.new do
loop do
logger.info %w[Howdy Hi Hey Yo Hohoho].sample << ", just checkin in"
sleep 2
if stop?
logger.info "Stopping ..."
break
end
end
end
end
def fork
Kernel.fork do
trap("INT") do
begin
puts "Shutting down ..."
Worker.stop
FileUtils.rm(LOG_FILE)
FileUtils.rm(PID_FILE)
rescue Errno::ENOENT
puts "Nothing to cleanup, log PID_FILE not found"
end
raise SignalException.new('INT') unless ENV["NORAISE"]
end
yield if block_given?
end
end
def stop
@exit = true
end
def stop?
!!@exit
end
def logger
@logger ||= Logger.new LOG_FILE
end
end
puts "Starting", "Monitor the process with:", "", " tail -f log/wb.log", ""
child = Worker.fork { Worker.call.join }
if ARGV.include?("-d")
puts "Daemonizing ..."
puts "Dumping PID #{child} to '#{PID_FILE}'"
File.open(PID_FILE, 'wb') { |f| f.puts(child) }
puts "Stop with: kill -INT `cat tmp/pids/wb.pid`"
puts "Done."
else
puts "Pass the -d option to daemonize. Press Ctrl-C to quit..."
Process.wait child
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment