当从命令行运行groovy脚本时,是否可以侦听CTRL + C?
我有一个创建一些文件的脚本.如果中断我想从磁盘中删除它们然后终止.
可能?
更新1:源自@tim_yates答案:
def withInteruptionListener = { Closure cloj, Closure onInterrupt ->
def thread = { onInterrupt?.call() } as Thread
Runtime.runtime.addShutdownHook (thread)
cloj();
Runtime.runtime.removeShutdownHook (thread)
}
withInteruptionListener ({
println "Do this"
sleep(3000)
throw new java.lang.RuntimeException("Just to see that this is also taken care of")
}, {
println "Interupted! Clean up!"
})
Run Code Online (Sandbox Code Playgroud)
tim*_*tes 12
以下应该有效:
CLEANUP_REQUIRED = true
Runtime.runtime.addShutdownHook {
println "Shutting down..."
if( CLEANUP_REQUIRED ) {
println "Cleaning up..."
}
}
(1..10).each {
sleep( 1000 )
}
CLEANUP_REQUIRED = false
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,(正如@DaveNewton指出的那样),"Shutting down..."当用户按下CTRL-C时会打印,或者进程正常完成,所以你需要一些方法来检测是否需要清理
为了好奇,以下是使用不受支持的sun.misc类的方法:
import sun.misc.Signal
import sun.misc.SignalHandler
def oldHandler
oldHandler = Signal.handle( new Signal("INT"), [ handle:{ sig ->
println "Caught SIGINT"
if( oldHandler ) oldHandler.handle( sig )
} ] as SignalHandler );
(1..10).each {
sleep( 1000 )
}
Run Code Online (Sandbox Code Playgroud)
但显然,这些类不能被推荐,因为它们可能会消失/改变/移动
| 归档时间: |
|
| 查看次数: |
2342 次 |
| 最近记录: |