Search code examples
clojure

How to make a Clojure go loop run forever


I want to use Clojure core.async to write an application that sits in a loop polling a service, but my attempts so far terminate unexpectedly.

When I run this program it prints the message then exits:

(defn -main
  []
  (println "Running forever...?")
  (async/go-loop [n 0]
                 (prn n)
                 (async/<!! (async/timeout 1000))
                 (recur (inc n))))

I would like the program to run forever (until the JVM process is killed).

What is the accepted way to achieve this?


Solution

  • The main thread is what will keep the JVM process running (it won't care about the threads in the go pool).

    Keep it running by blocking on the main thread. e.g.

    (defn -main
      []
      (println "Running forever...?")
      (async/<!! (async/go-loop [n 0]
                     (prn n)
                     (async/<! (async/timeout 1000))
                     (recur (inc n)))))
    

    Note: you shouldn't use <!! inside of a go block. You should instead use <!.