Skip to content

Instantly share code, notes, and snippets.

@danownsthisspace
Created December 4, 2021 13:29
Show Gist options
  • Save danownsthisspace/ccce16ce2c278c3c7618998fe93de766 to your computer and use it in GitHub Desktop.
Save danownsthisspace/ccce16ce2c278c3c7618998fe93de766 to your computer and use it in GitHub Desktop.
Start of rate limit video. there is a bug where the wrap-once-in-a-while function is not thread safe
(ns scratch.core)
(defn say-hi [username]
(let [s (str "hello, " username)]
(Thread/sleep (rand 100))
(println s)
s))
(defn wrap-once-in-a-while [msecs-period f]
(let [last-executed_ (atom 0)]
(fn wrapper [& args]
(let [now (System/currentTimeMillis)
last-executed @last-executed_
elapsed (- now last-executed)]
(when (>= elapsed msecs-period)
(let [result
(try
(do {:okay (apply f args)})
(catch Throwable t {:error t}))]
(reset! last-executed_ now)
result))))))
(comment
(let [wf (wrap-once-in-a-while 100 say-hi)]
[(wf "on the code again")
(wf "on the code again")
(wf "on the code again")]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment