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!"
})
The following should work:
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 requiredUpdate
For the sake of curiosity, here is how you would do it using the unsupported
sun.miscclasses:But obviously, those classes can’t be recommended as they might disappear/change/move