Skip to content

Instantly share code, notes, and snippets.

@mrowe
Last active July 20, 2020 18:09
Show Gist options
  • Save mrowe/4689005 to your computer and use it in GitHub Desktop.
Save mrowe/4689005 to your computer and use it in GitHub Desktop.
A first attempt at a polling loop in clojure...
;; 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