我想有一个调度异步任务的方法,并立即返回。我不需要等待结果。 我喜欢这样的事情:
/**
* runs a job and return job id for later montoring.
*/
def int runJob(){
int jobId = createJob() // returns immediately
task{
doSomthingThatTakesSomeTime()
}.then {stepResult-> doSmtgElse(stepResult)}
return jobId
}
在上面的情况中,任务不会运行,因为没有.get()的调用 但是,如果我执行.get(),则该方法在任务完成之前不会返回jobId。
我如何发送任务并仍然立即返回?
答案 0 :(得分:1)
您可以将此示例作为Groovy脚本运行:
@Grapes(
@Grab(group='org.codehaus.gpars', module='gpars', version='1.2.1')
)
import java.util.concurrent.*
import groovyx.gpars.*
def doSomethingThatTakesSomeTime(){
println "calculating..."
for(long i: 0..100){
Thread.sleep(i)
}
println "*done*"
"Done with doSomethingThatTakesSomeTime"
}
def doSomethingElse(){
for(int x:0..1000) print "."
println "doSomethingElse done."
}
/**
* runs a job and return job id for later montoring.
*/
def runJob(){
GParsPool.withPool(){
Future future = createJob() // returns immediately
doSomethingElse() //Do someting else while the async process is running
//Ok, thats done, but the longer runningprocess is still running, return the future
future
}
}
Future createJob(){
//create a new closure, which starts the original closure on a thread pool
Closure asyncFunction = { doSomethingThatTakesSomeTime() }.async()
//Invoke the function, return a Future
asyncFunction()
}
def job = runJob()
//println "\n\nResult is: " + job.get()
如果您运行脚本"原样",您将看到它运行且长时间运行的作业确实打印*done*
,表明它确实运行完成,即使该行在底部,调用Future.get()
被注释掉,从未被调用。
如果您取消注释最后一行,则会在调用Future.get()
答案 1 :(得分:1)
在阅读了@pczeus的回答和JérémieB的评论后,我想出了这个:
import static groovyx.gpars.dataflow.Dataflow.task
def int longTask(){
def counter = 0
10.times {
println "longTask_${counter}"
counter++
sleep 10
}
counter
}
def int getSomeString() {
def jobId=55
task {
longTask()
}.then { num -> println "completed running ${num} times" }
return jobId
}
println getSomeString()
sleep 2000
打印:
longTask_0
55
longTask_1
longTask_2
longTask_3
longTask_4
longTask_5
longTask_6
longTask_7
longTask_8
longTask_9
completed running 10 times
这是我的意图: longTask()在后台运行,getSomeString()在不等待长任务的情况下重新运行,只要程序仍然在运行(因此是sleep 2000),即使是'then'部分中的子句也会被执行< / p>