Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way for a Grails Service class to detect application shutdown?

I have a Grails service class that needs to do some cleanup when my Tomcat application server is shut down.

I don't see anything in the Grails docs about a service.stop() or destroy() method, or a way to implement any sort of application lifecycle listener.

What's the best way to do this?

Thanks!

like image 715
Dean Moses Avatar asked Apr 05 '11 21:04

Dean Moses


3 Answers

The grails-app/conf/BootStrap.groovy can be used when the app starts and stops.

def init = {
  println 'Hello World!'
}

def destroy = {
  println 'Goodnight World!'
}

Note: When using development mode grails run-app on some OS's CTL+C will kill the JVM without the chance for a clean shutdown and the destroy closure may not get called. Also, if your JVM gets the kill -9 the closure wont run either.

like image 39
Derek Slife Avatar answered Oct 04 '22 18:10

Derek Slife


You have a couple of options

Make your service implement org.springframework.beans.factory.DisposableBean

class MyService implements org.springframework.beans.factory.DisposableBean {

    void destroy() throws Exception {

    }
}

Or use an annotation

class MyService {

    @PreDestroy
    private void cleanUp() throws Exception {

    }
 }

IMO, the annotation option is preferable, because you can give your destructor method a more meaningful name than destroy and your classes public API doesn't expose the Spring dependency

like image 136
Dónal Avatar answered Oct 04 '22 18:10

Dónal


I would try injecting the service into the Bootstrap and then calling the method from the destroy block, since the destroy block is executed when the application is terminated, something like this:

class BootStrap {

    def myService

    def init = {servletContext ->
    }

    def destroy = {
       myService.cleanUp()
    }
}
like image 25
Maricel Avatar answered Oct 04 '22 16:10

Maricel