简体   繁体   English

如何使Clojure go循环永远运行

[英]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. 我想使用Clojure core.async来编写一个循环轮询服务的应用程序,但我的尝试到目前为止意外终止。

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). 我希望程序永远运行(直到JVM进程被终止)。

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). 主线程将保持JVM进程运行(它不关心go池中的线程)。

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. 在一个go块里面。 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 ). (或者你可以使用Long/MAX_VALUE )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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