Search

Dark theme | Light theme

January 5, 2010

Groovy Goodness: Add a ShutdownHook

If we want to execute some code when our Groovy script or application is stopped we can use the addShutdownHook() method. We pass a closure to this method, which is executed when our Groovy script or application stops. This can be a normal termination, but the closure is also executed when the application is stopped by user input (Ctrl+C) or a system event like a shutdown.

addShutdownHook {
    println ''  
    println 'Script is ended.'
}

println 'Script is started.'
println 'Press Ctrl+C to stop this script or wait 10 seconds.'
(1..10).each {
    print "..$it"
    Thread.sleep 1000
}