groovy.transform
[Groovy] Annotation Type TimedInterrupt
java.lang.Object
groovy.transform.TimedInterrupt
@Retention(RetentionPolicy.SOURCE)
@Target([ ElementType.METHOD, ElementType.TYPE])
@GroovyASTTransformationClass(["org.codehaus.groovy.transform.TimedInterruptibleASTTransformation"])
@interface TimedInterrupt
Allows safe timed executions of scripts by adding elapsed time checks on loops (for, while, do), the first statement
of closures, and the first statement of methods.
This is especially useful when executing foreign scripts that you do not have control over. Inject this
transformation into a script that you want to timeout after a specified amount of timet.
Annotating anything in a script will cause for loops, while loops, methods, and closures to make an
elapsed time check and throw a TimeoutException if the check yields true. The annotation by default
will apply to any classes defined in the script as well. Annotated a class will cause (by default) all classes
in the entire file ('Compilation Unit') to be enhanced. You can fine tune what is enhanced using the annotation
parameters. Static methods and static fields are ignored.
Extensive usage examples can be found in the unit test for this class. A smaller example is presented here.
The following is sample usage of the annotation forcing the script to timeout after 1000 seconds:
import groovy.transform.TimedInterrupt
import java.util.concurrent.TimeUnit
@TimedInterrupt(value = 1000L, unit = TimeUnit.SECONDS)
class MyClass {
def method() {
println '...'
}
}
This sample script will be transformed at compile time to something that resembles this:
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
public class MyClass {
final private long TimedInterrupt$expireTime
final private java.util.Date TimedInterrupt$startTime
public MyClass() {
TimedInterrupt$expireTime = System.nanoTime() + TimeUnit.NANOSECONDS.convert(1000, TimeUnit.SECONDS)
TimedInterrupt$startTime = new java.util.Date()
}
public java.lang.Object method() {
if (TimedInterrupt$expireTime < System.nanoTime()) {
throw new TimeoutException('Execution timed out after 1000 units. Start time: ' + TimedInterrupt$startTime)
}
return this.println('...')
}
}
- Authors:
- Hamlet D'Arcy
- See Also:
- ThreadInterrupt
- ConditionalInterrupt
- Since:
- 1.8.0
Copyright © 2003-2011 The Codehaus. All rights reserved.