Skip to content

Instantly share code, notes, and snippets.

@gitanat
Created October 15, 2013 15:13
Show Gist options
  • Save gitanat/6993168 to your computer and use it in GitHub Desktop.
Save gitanat/6993168 to your computer and use it in GitHub Desktop.
ping periodically and print results
import subprocess
import sched
import threading
from functools import partial
import time
from datetime import datetime
def ping( host, count=1, timeout=5):
count, timeout= map(str, (count, timeout))
devnull= open("/dev/null","w")
result= subprocess.call( ["ping", "-c", count, "-w", timeout, host], stdout=devnull, stderr=devnull)
return result==0
def repeat( f, interval ):
extra= 0.5-(datetime.utcnow().microsecond/1000000.0) #try to fire event always on the middle of system second
extra*=0.01 #gradual
stable_interval= interval+extra #avoid accumulated error because of function call time
if keep_running:
threading.Timer(stable_interval, repeat, (f,interval) ).start()
f()
def log(f):
date, result= datetime.utcnow(), f()
log_lock.acquire()
print date,result
log_lock.release()
log_lock= threading.Lock()
keep_running=True
ping_f= partial(ping, "yahoo.com", timeout=1)
log_f= partial(log, ping_f)
repeat( log_f, 1)
while True:
try:
time.sleep(1)
except KeyboardInterrupt:
keep_running=False
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment