如何解决Groovy 意外输入:@TimedInterrupt

How to solve Groovy Unexpected input: @TimedInterrupt

我试图通过导入 groovy class TimedInterrupt 来执行以下 groovy 脚本,不幸的是无法理解编译错误背后的原因。我已经提到 groovyOfficial documentation and have also looked at some resources here 但无法取得重大进展。如果 groovy 专家在解决此问题时提供任何宝贵意见,我将不胜感激。

import groovy.transform.TimedInterrupt
import java.util.concurrent.TimeUnit

def buildInterrupt() {
    @TimedInterrupt(value = 3L, unit = TimeUnit.MICROSECONDS)
}

def timeout_method() {
    println 'This is for testing: '
}
 
buildInterrupt() //this invocation is necessary in the long run
time_method()

Post Execution
1 compilation error:

Unexpected input: '@TimedInterrupt(value = 3L, unit = TimeUnit.MICROSECONDS)\n}' at line: 6, column: 1

我需要定时中断生效,预期输出如下

Exception thrown

java.util.concurrent.TimeoutException: Execution timed out after 3 microseconds. Start time: Thu Mar 14 12:28:09 IST 2020
at timeout_method.run(timeout_method.groovy)

谢谢

我相信您 运行 陷入编译问题的原因是注释(在本例中为 TimedInterrupt)需要注释 class、成员变量、方法等。在您的情况下,注释应用于“没有任何注释”的位置。

以下代码:

import groovy.transform.TimedInterrupt
import java.util.concurrent.TimeUnit

@TimedInterrupt(value = 500L, unit = TimeUnit.MILLISECONDS)
def somethingToAnnotate = 0

def methodA() {
  // sleep 100 ms
  100.times { Thread.sleep(1) }
  println 'hello from method a'
}

10.times { 
  methodA()
}

工作并打印:

─➤ groovy solution.groovy
hello from method a
hello from method a
hello from method a
hello from method a
Caught: java.util.concurrent.TimeoutException: Execution timed out after 500 milliseconds. Start time: Fri Mar 26 12:11:14 CET 2021
java.util.concurrent.TimeoutException: Execution timed out after 500 milliseconds. Start time: Fri Mar 26 12:11:14 CET 2021
    at solution$_methodA_closure2.doCall(solution.groovy)
    at solution.methodA(solution.groovy:9)
    at solution$_run_closure1.doCall(solution.groovy:14)
    at solution.run(solution.groovy:13)

─➤

此处注释应用于变量。

需要注意的是,在groovy脚本中,如果你注解了一个方法,那么超时是在定义方法时开始的,而不是在执行时开始的。换句话说,即使方法永远不会 运行.

,注释方法和 运行ning 脚本也会开始超时