Last active
July 20, 2020 18:09
-
-
Save mrowe/4689005 to your computer and use it in GitHub Desktop.
A first attempt at a polling loop in clojure...
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
;; Based on a queue polling function from Chas Emerick's bandalore: | |
;; https://github.com/cemerick/bandalore/blob/master/src/main/clojure/cemerick/bandalore.clj#L124 | |
(defn wait-for | |
"Invoke predicate every interval (default 10) seconds until it returns true, | |
or timeout (default 150) seconds have elapsed. E.g.: | |
(wait-for #(< (rand) 0.2) :interval 1 :timeout 10) | |
Returns nil if the timeout elapses before the predicate becomes true, otherwise | |
the value of the predicate on its last evaluation." | |
[predicate & {:keys [interval timeout] | |
:or {interval 10 | |
timeout 150}}] | |
(let [end-time (+ (System/currentTimeMillis) (* timeout 1000))] | |
(loop [] | |
(if-let [result (predicate)] | |
result | |
(do | |
(Thread/sleep (* interval 1000)) | |
(if (< (System/currentTimeMillis) end-time) | |
(recur))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment