有没有Groovy等价于Ruby Timeout模块的功能?

3
在Ruby中,我会使用Timeout模块,它执行一个代码块,并且如果超过了设定的时间,就会停止执行该代码块。
require 'timeout'
status = Timeout::timeout(5) {
  # Something that should be interrupted if it takes too much time...
}

Groovy有类似这样的功能吗?
1个回答

4

有一个名为TimedInterrupt注解,但我还没有尝试过...

我进行了快速测试,这是一个(不好的)例子:

@groovy.transform.TimedInterrupt( 5L )
def loopy() {
  int i = 0
  try {
    while( true ) {
      i++
    }
  }
  catch( e ) {
    i
  }
}

println loopy()

在Groovy控制台中运行并在5秒后打印出i
我的输出为:
47314150

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接