Monday, July 29, 2013

Sending Email Asynchronously in Grails

Sending Email Asynchronously in Grails

You are working on a project and during one of the transactions there has to be a lot of emails sent but you dont want to keep the user's response waiting for all those emails to send then you want to do it asynchronously. In my grails application I am using the mail plugin (version 1.0.1) and for asynchronous activities I am using plugin executor plugin (version 0.3). The combination of the two plugins allowed me to send all my mails in the background without the user waiting. Here is how:

To setup the mail plugin:
http://grails.org/plugin/mail

To setup executor service:
http://grails.org/plugin/executor

1. In your resources.groovy add this bean

executorService( grails.plugin.executor.PersistenceContextExecutorWrapper ) { bean->
    bean.destroyMethod = 'destroy'
    persistenceInterceptor = ref("persistenceInterceptor")
    executor = Executors.newCachedThreadPool()
}
You can override and use your own custom thread pool but for this task lets go basic.
 
2. In any controller where you want to use the executor service you can inject it
def 
3. For simplicity like I did use the shortcut methods runAsync which takes any closure
4. In runAsync put your sendMail calls to send email 
 
runAsync {

      sendMail {
          ....
      }
}
 
It worked for me so well hope you are able to find it useful too. 

2 comments:

  1. The Asynchronous Mail plugin is more useful for message sending.

    ReplyDelete
  2. You could have explained more elaborately.

    ReplyDelete