简体   繁体   中英

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?

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. eg

(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 <! .

How many ways are there to block the main thread......?

(defn -main []
  (println "Running forever...?")

  ; go-loop runs forever in another (daemon) thread
  (async/go-loop [n 0]
                 (prn n)
                 (async/<!! (async/timeout 1000))
                 (recur (inc n))

  ; hang the main thread
  (Thread/sleep 111222333444))  ; long enough....

(or you could use Long/MAX_VALUE ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM