A Groovy way to retry method calls in case of exceptions

In some scenarios, method calls can fail – but would succeed when retrying the call after some seconds have passed.

That is often the case with remote method calls, where the remote application could be temporarily unavaillable.

I needed a simple way to define something like

“call method foo(). In case the method throws an Exception, retry to call it up to 10 times with a delay of 3 seconds”.

I implemented a simple Groovy util class which enabled me to write code as follows:

RetryUtil.retry(10, 3000){
	foo()
}

Here is the sourcecode of the RetryUtil Groovy class:

import org.apache.commons.logging.LogFactory
import org.apache.commons.logging.Log

class RetryUtil {

	private static Log log = LogFactory.getLog(RetryUtil);

	static retry(int times, long sleeptime, Closure c){
		Throwable catchedThrowable = null
		for(int i=0; i<times; i++){
			try {
				return c.call()
			} catch(Throwable t){
				catchedThrowable = t
				log.warn("failed to call closure. ${i+1} of $times runs.")
				Thread.sleep(sleeptime)
			}
		}
		log.error("finally failed to call closure after $times tries.")
		throw catchedThrowable
	}
}
Dieser Beitrag wurde unter Groovy and Grails abgelegt und mit , verschlagwortet. Setze ein Lesezeichen auf den Permalink.

Eine Antwort zu A Groovy way to retry method calls in case of exceptions

  1. Pingback: Grails cette semaine (2011-12) – Traduction de l’article original

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Verbinde mit %s