当clojure未来结束时,有没有办法得到通知?

时间:2013-05-02 23:33:30

标签: clojure

有没有办法在未来设置监视器,以便在完成后触发回调?

这样的事情?

> (def a (future (Thread/sleep 1000) "Hello World!")
> (when-done a (println @a))

...waits for 1sec...
;; =>  "Hello World"

5 个答案:

答案 0 :(得分:9)

您可以启动另一项监视未来的任务,然后运行该功能。在这种情况下,我将只使用另一个未来。哪个很好地包含在完成功能中:

user=> (defn when-done [future-to-watch function-to-call] 
          (future (function-to-call @future-to-watch)))
user=> (def meaning-of-the-universe 
         (let [f (future (Thread/sleep 10000) 42)] 
            (when-done f #(println "future available and the answer is:" %)) 
            f))
#'user/meaning-of-the-universe

... waiting ...

user=> future available and the answer is: 42
user=> @meaning-of-the-universe
42

答案 1 :(得分:2)

对于非常简单的情况: 如果您不想阻止并且不关心结果,只需在将来的定义中添加回调。

(future (a-taking-time-computation) (the-callback))

如果你关心结果,请使用comp回调

(future (the-callback (a-taking-time-computation)))

(future (-> input a-taking-time-computation callback))

从语义上讲,java等效代码将是:

final MyCallBack callbackObj = new MyCallBack();
new Thread() {
     public void run() {
         a-taking-time-computation();
         callbackObj.call();
     }
 }.start()

对于复杂的案例,您可能需要查看:

https://github.com/ztellman/manifold

https://github.com/clojure/core.async

答案 2 :(得分:1)

答案 3 :(得分:0)

我没有利用Thread/Sleep来增加时间,而是利用@future-ref来指代将来会一直等到将来完成。

(defn  wait-for
  [futures-to-complete]
  (every? #(@%) futures-to-complete))

答案 4 :(得分:0)

已接受答案的扩展名

请注意以下警告:

使用上述when-done实现,将不会调用该回调 如果未来被取消。 那是

(do
  (def f0 (future (Thread/sleep 1000)))
  (when-done f0 (fn [e] (println "THEN=>" e)))
  (Thread/sleep 500)
  (future-cancel f0))

将不会打印,因为已取消的调用被取消 未来将引发例外。

如果需要回调,我建议:

(defn then
  "Run a future waiting on another, and invoke
  the callback with the exit value if the future completes,
  or invoke the callback with no args if the future is cancelled"
  [fut cb]
  (future
    (try
      (cb @fut)
      (catch java.util.concurrent.CancellationException e
        (cb)))))

所以现在将打印:

  (do
    (def f0 (future (Thread/sleep 1000)))
    (then f0 (fn
               ([] (println "CANCELLED"))
               ([e] (println "THEN=>" e))))
    (Thread/sleep 500)
    (future-cancel f0))