haxx populi

Spring ScheduledExecutors in Grails

by jja on
Topics:

Here's how to setup scheduled (periodic or timed) tasks with Spring3 in Grails using the concurrency executors introduced in Java5. This replaces the use of a Spring2 TimerTask which was deprecated in Spring3 and removed from Spring4. Grails2 uses Spring3 so the TimerTask should still work, but this method should work in Grails2 and Grails3. Note that in Grails3 and possibly 2.4/2.5, you might be able to use the much simpler Spring @Scheduled annotation on a service method.

Thanks to the blog at henyo for the inspiration, with their post on Spring2 TimerTask usage in Grails1.

In Grails 2.x, add something like this in your grails-app/conf/spring/resources.groovy (following/updated from henyo):

myInvoker(org.springframework.scheduling.support.MethodInvokingRunnable) {
    targetObject = ref('myService')
    targetMethod = 'myMethod'
}

myScheduler(org.springframework.scheduling.concurrent.ScheduledExecutorTask) {
    // in Config.groovy, set mykey.delay and mykey.period
    // milliseconds, 600000ms = 10min
    delay = grailsApplication.config.mykey.delay ?: 600000
    period = grailsApplication.config.mykey.period ?: 600000
    runnable = ref('myInvoker')
}

myFactory(org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean) {
    scheduledExecutorTasks = [ref('myScheduler')]
}

Then of course you will need a myService class with a myMethod method that takes no arguments.

(comments are closed)