等待超时的多个异步 gpars 数据流任务

Waiting on multiple async gpars dataflow tasks with timeout

我正在努力实现拥有多个一般超时的异步任务的目标。诀窍是我需要处理超时内收到的任何内容。

例如,当超时值超过两秒时,下面的代码获取两个任务的值。但是一旦超时减少(或者任务花费的时间更长),只会抛出 TimeoutException 并且 none 会收到任务结果。

def timeout = 3  // value in seconds

def t1 = task {
    Thread.sleep(1000)
    println 't1 done'
    't1'
}

def t2 = task {
    Thread.sleep(2000)
    println 't2 done'
    't2'
}

def results = whenAllBound( [t1, t2] ) { List l ->
    println 'all done ' + l
    l.join(', ')
}.get( timeout, SECONDS )

println "results $results"

而不是 get() 使用 join() 不会抛出 TimeoutException,但它也不会 return 最终结果并在超时到期后继续处理代码。

我不理解数据流结构 fully/enough/correctly,我试图错误地使用它们,或者两者都有。

基本上我需要的是一个同步块,它可以触发多个具有共同超时的异步作业,return处理超时发生时可用的任何响应。超时更像是一种例外情况,但确实偶尔会发生在每个任务中,并且不应影响整体处理。

也许这种方式适合你:

whenAllBound( [t1, t2] ) { List l ->
    println 'all done ' + l
    l.join(', ')
}.join( timeout, java.util.concurrent.TimeUnit.SECONDS )

def results = [t1, t2].collect {it.bound ? it.get() : null}
println "results $results"