【问题标题】:How to solve Groovy Unexpected input: @TimedInterrupt如何解决 Groovy 意外输入:@TimedInterrupt
【发布时间】:2021-03-25 19:40:55
【问题描述】:

我正在尝试通过导入 groovy 类 TimedInterrupt 来执行以下 groovy 脚本,遗憾的是无法理解编译错误背后的原因。我参考了groovyOfficial 文档,还查看了一些资源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)

谢谢

【问题讨论】:

    标签: java groovy interrupt-handling


    【解决方案1】:

    我相信您遇到编译问题的原因是注释(在本例中为 TimedInterrupt)需要注释类、成员变量、方法等。在您的情况下,注释应用于某个位置它“没有什么可注释的”。

    以下代码:

    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 脚本中,如果你注解了一个方法,超时是在定义方法时开始的,而不是在它执行时。换句话说,注解一个方法并运行脚本将启动超时,即使该方法从未运行过。

    【讨论】:

    • 非常感谢您的回复,您的回答是最好的。
    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 2016-09-28
    相关资源
    最近更新 更多