Created
May 23, 2017 21:11
-
-
Save joshjones/cec1b154d50888203bd9a399645b256e to your computer and use it in GitHub Desktop.
Methods to stop a loop from executing.
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
(defn ping-forever-core-async | |
[host ms-pause] | |
(let [termination-ch (chan) | |
termination-fn #(put! termination-ch :die)] | |
(go-loop [sleep-ch (timeout 0)] | |
(let [[_ ch] (alts! [sleep-ch termination-ch])] | |
(if (= ch sleep-ch) | |
(do | |
(println "Pinging" host) | |
(recur (timeout ms-pause))) | |
(println "Stopping...")))) | |
termination-fn)) | |
(defn ping-forever-thread | |
[host ms-pause] | |
(let [t (Thread. #(try | |
(while true | |
(println "Pinging " host) | |
(Thread/sleep ms-pause)) | |
(catch InterruptedException e | |
(println "Stopping...")))) | |
termination-fn #(.interrupt t)] | |
(.start t) | |
termination-fn)) | |
(defn ping-forever-flag | |
[host ms-pause] | |
(let [keep-going (atom true) | |
stop-fn #(reset! keep-going false)] | |
(future (while @keep-going | |
(println "Pinging" host) | |
(Thread/sleep ms-pause)) | |
(println "Stopping...")) | |
stop-fn)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment