Is there a Groovy equivalent of a Ruby time-out module?

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

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

Does Groovy have something like this?

+3
source share
1 answer

There is an annotation TimedInterrupt , but I have not tried it yet ...

Give it a quick test, and this one (bad example):

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

println loopy()

Runs in the groovy console and displays iafter 5 seconds.

I get:

47314150
+4
source

All Articles