Skip to content

Instantly share code, notes, and snippets.

@davidvhill
Last active September 21, 2020 14:45
Show Gist options
  • Save davidvhill/c71ec05730994e5f1fb1f39b2dd57dd6 to your computer and use it in GitHub Desktop.
Save davidvhill/c71ec05730994e5f1fb1f39b2dd57dd6 to your computer and use it in GitHub Desktop.
Function with Retry
;; Returns a function with retries.
;; retries: num of retries
;; delay: delay between retries in milliseconds
;; f: function to apply
;; ef: error function, determines if f should be retried
;; f and ef should not throw Exceptions
(defn with-retry
[retries delay f ef]
(fn [& args]
(loop [retry 1]
(let [result (apply f args)]
(if (and (ef result) (<= retry retries))
(do (Thread/sleep delay)
(recur (inc retry)))
result)))))
;;
;; (f) will retry 5 times with a 2 second delay and finally return {:error true}
;; (def f (with-retry 5 2000 (fn [] {:error true}) :error))
;;
;; (g) will run successfully on the first attempt
;; (def g (with-retry 5 2000 (fn [] {:x 1 :y 2}) :error))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment