Skip to content

Instantly share code, notes, and snippets.

@arctickiwi
Last active February 25, 2016 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arctickiwi/54f7ea49fee039b14a3e to your computer and use it in GitHub Desktop.
Save arctickiwi/54f7ea49fee039b14a3e to your computer and use it in GitHub Desktop.
Long-running task which periodically checks the internet connection by pinging Google's DNS server and reporting outages
require 'net/ping'
HOST = '8.8.4.4'
start = Time.now
puts "#{start} Starting connection check. Pinging #{HOST}"
icmp = Net::Ping::ICMP.new(HOST)
@down = false
total = 0
begin
while true
success = false
begin
success = icmp.ping
rescue StandardError
success = false
end
if success && @down
down_for = Time.now - @dropped
puts "#{Time.now} Connection back up (down for #{down_for.round}s)"
total += down_for
@dropped = nil
elsif !success && !@down
@dropped = Time.now
puts "#{@dropped} Connection is down"
end
@down = !success
sleep 5
end
rescue SystemExit, Interrupt
finish = Time.now
total += (finish - @dropped) if @dropped # incase Ctrl-C while down
puts "#{finish} finishing. Ran for #{(finish - start).round}s. Down for a total of #{total.round}s"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment