有没有办法通知,当clojure未来完成? [英] Is there a way to be notified when a clojure future finishes?

查看:139
本文介绍了有没有办法通知,当clojure未来完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to set a watch on a future so that it triggers a callback when it is done?

这样的东西?

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

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


推荐答案

您可以启动另一个任务来观察未来,然后运行该函数。在这种情况下,我将使用另一个未来,它很好地包装到一个when-done函数中:

You can start another task that watches the future and then runs the function. In this case I'll just use another future. Which wraps up nicely into a when-done function:

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

这篇关于有没有办法通知,当clojure未来完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆