在My Grails服务中,我希望以异步方式运行一部分方法。
以下是2.3.x http://grails.org/doc/2.3.0.M1/guide/async.html
的文档我做
public class MyService {
public void myMethod() {
Promise p = task {
// Long running task
}
p.onError { Throwable err ->
println "An error occured ${err.message}"
}
p.onComplete { result ->
println "Promise returned $result"
}
// block until result is called
def result = p.get()
}
}
但是,我想在没有任何阻挡的情况下执行我的。 p.get()
方法阻止。如何在没有任何阻塞的情况下执行promise。我不在乎myMethod()
是否返回,它是一种火与忘记的方法。
答案 0 :(得分:14)
所以,根据documentation,如果你不打电话给.get()
或.waitAll()
,而只是使用onComplete
,你就可以不受阻碍地运行你的任务当前的主题。
这是一个非常愚蠢的例子,我在控制台中作为概念证明。
import static grails.async.Promises.*
def p = task {
// Long running task
println 'Off to do something now ...'
Thread.sleep(5000)
println '... that took 5 seconds'
return 'the result'
}
p.onError { Throwable err ->
println "An error occured ${err.message}"
}
p.onComplete { result ->
println "Promise returned $result"
}
println 'Just to show some output, and prove the task is running in the background.'
运行上面的示例会给出以下输出:
Off to do something now ...
Just to show some output, and prove the task is running in the background.
... that took 5 seconds
Promise returned the result