有没有办法在未来设置监视器,以便在完成后触发回调?
这样的事情?
> (def a (future (Thread/sleep 1000) "Hello World!")
> (when-done a (println @a))
...waits for 1sec...
;; => "Hello World"
答案 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()
对于复杂的案例,您可能需要查看:
答案 2 :(得分:1)
我在google上找到了这个看起来很有趣的帖子:
https://groups.google.com/forum/?fromgroups=#!topic/clojure-dev/7BKQi9nWwAw
http://dev.clojure.org/display/design/Promises
https://github.com/stuartsierra/cljque/blob/master/src/cljque/promises.clj
答案 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))