Home Execute task after transaction ends - Grails
Reply: 2

Execute task after transaction ends - Grails

Lucas Milotich
Lucas Milotich Published in 2017-11-28 18:39:01Z

I need to execute some tasks after grails transaction ends. I'm not looking for afterCommit of Hibernate, instead of that, I need a method to be called after the transaction of the service ends.

Is there any way? I've read the documentation but I couldn't find anything, just normal events like afterUpdate or afterCommit.


Trebla Reply to 2017-11-29 21:20:57Z

That really depends on what you're trying to do. The best bet is probably to call a @Transactional method on a service, and then when that returns, run the code that you need to happen after the transaction.

An alternative, if you just want to spin off some task to do something simple, you can use:

new java.util.Timer().runAfter(1000) { //time in milliseconds
  //code to run here

This is just a shortcut to spin off a new thread and runs the closure body after (in the above example) 1 second... I believe the closure still has access to injected grails objects, but does not have access to the session. I'd double-check that though. I've used this in several places for sending notifications that needed to wait until after some processing inside a transaction ended.

James Kleeh
James Kleeh Reply to 2017-11-30 16:03:10Z

You can add an event listener to the current session


class MyListener extends BaseSessionEventListener {
    void transactionCompletion(boolean successful) {


You just need to verify the transaction was successful via the parameter. Also understand that if there are multiple transactions in a single session the listener will be invoked for each one.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304754 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO