Last active
February 25, 2016 16:30
-
-
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
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 '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