Reputation: 22369
Is it possible to listen to CTRL+C when a groovy script is run from the command line ?
I have a script that creates some files. If interrupted I want to delete them from disk and then terminate.
Possible?
UPDATE 1: Derived from @tim_yates answer:
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!"
})
Upvotes: 6
Views: 3069
Reputation: 171114
The following should work:
CLEANUP_REQUIRED = true
Runtime.runtime.addShutdownHook {
println "Shutting down..."
if( CLEANUP_REQUIRED ) {
println "Cleaning up..."
}
}
(1..10).each {
sleep( 1000 )
}
CLEANUP_REQUIRED = false
As you can see, (as @DaveNewton points out), "Shutting down..."
will be printed when the user presses CTRL-C, or the process finishes normally, so you'd need some method of detecting whether cleanup is required
For the sake of curiosity, here is how you would do it using the unsupported sun.misc
classes:
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 )
}
But obviously, those classes can't be recommended as they might disappear/change/move
Upvotes: 12
Reputation: 1422
I am not much into groovy script but i have a link that have some examples and says catching ctrl+c.....hope that helps http://pleac.sourceforge.net/pleac_groovy/processmanagementetc.html
Upvotes: 2