Last active
August 29, 2015 13:56
-
-
Save zentrope/8838672 to your computer and use it in GitHub Desktop.
two async loops for pinging a host
This file contains 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
(ns cping.core | |
(:gen-class) | |
(:require [clojure.java.shell :as shell :refer [sh]] | |
[clojure.core.async :refer [queue go-loop timeout chan <! put!]])) | |
(defn- ping! | |
"Use the shell to ping the given host" | |
[host] | |
(sh "ping" "-W" "1" "-c" "1" host)) | |
(defn ping-loop! | |
"Runs a function after waiting 'millis'. Runs forever." | |
[queue host millis] | |
(go-loop [] | |
(<! (timeout millis)) | |
(put! queue (ping! host)) | |
(recur))) | |
(defn ping-handler! | |
[queue] | |
(go-loop [sec 1, good-old 0] | |
(when-let [result (<! queue)] | |
(let [{:keys [out exit] :as result} result | |
good? (zero? exit) | |
good (if good? (inc good-old) good-old) | |
last? (= sec 60)] | |
(print (if good? "#" ".")) | |
(flush) | |
(if last? | |
(do | |
(println (summarize good)) | |
(recur 1 0)) | |
(recur (inc sec) good)))))) | |
(defn -main | |
[host & args] ;; not sure if this destructuring works here | |
(let [hold (promise) | |
queue (chan)] | |
(ping-handler! queue) | |
(ping-loop! queue host 1000) | |
@lock | |
(System/exit 0))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could also use (thread ...) rather than (go-loop [] ...) and then use the !! variants for taking and putting to the queues.