Ruby Timeout模块有Groovy等价物吗? [英] Is there a Groovy equivalent of the Ruby Timeout module?

查看:122
本文介绍了Ruby Timeout模块有Groovy等价物吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,我会使用Timeout模块,它会执行一个模块,并在超时时间内停止执行代码。

In Ruby I would use the Timeout module, where it executes a block and will stop executing the code if it passes the timeout.

require 'timeout'
status = Timeout::timeout(5) {
  # Something that should be interrupted if it takes too much time...
}

Groovy是否具有类似的功能?

Does Groovy have something like this?

推荐答案

TimedInterrupt 注释,但我还没有尝试过......

There is the TimedInterrupt annotation, but I've not tried it out yet...

给它一个快速测试,这个(不好的例子):

Gave it a quick test, and this (poor example):

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

println loopy()

在groovy控制台中运行打印出 5秒后。

Runs in the groovy console and prints out i after 5 seconds.

我得到:

I get:

47314150

这篇关于Ruby Timeout模块有Groovy等价物吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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