Periodically calling a function in Clojure

Drew Noakes picture Drew Noakes · Jan 28, 2014 · Viewed 9.7k times · Source

I'm looking for a very simple way to call a function periodically in Clojure.

JavaScript's setInterval has the kind of API I'd like. If I reimagined it in Clojure, it'd look something like this:

(def job (set-interval my-callback 1000))

; some time later...

(clear-interval job)

For my purposes I don't mind if this creates a new thread, runs in a thread pool or something else. It's not critical that the timing is exact either. In fact, the period provided (in milliseconds) can just be a delay between the end of one call completing and the commencement of the next.

Answer

A. Webb picture A. Webb · Jan 28, 2014

If you want very simple

(defn set-interval [callback ms] 
  (future (while true (do (Thread/sleep ms) (callback)))))

(def job (set-interval #(println "hello") 1000))
 =>hello
   hello
   ...

(future-cancel job)
 =>true

Good-bye.