Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Periodically calling a function in Clojure

Tags:

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.

like image 772
Drew Noakes Avatar asked Jan 28 '14 11:01

Drew Noakes


1 Answers

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.

like image 159
A. Webb Avatar answered Oct 17 '22 14:10

A. Webb