Friday, November 21, 2008

Simple Periodic Task Scheduling with Grails

Need to run a periodic background task in your grails app? Here's how you can do it with no additional plug-ins. I tried this with Grails version 1.03 but I believe its valid even for older versions. This approach assumes that you need to execute a method in one of your service components periodically. In this example, I need to run the doFoo() method of the FooService every minute with an initial delay of 1 minute. Open the resources.groovy file located in the spring folder inside your conf folder inside the grails-app directory of your project. So if your project is in a directory myproject, you can find it at ~/myproject/grails-app/conf/spring Add or modify the contents of the file to include the following declarations:
beans = {
    doFooTimerTask(org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean){
        targetObject = ref("fooService")
        targetMethod = 'doFoo'
    }
    
    doFooScheduledTimerTask(org.springframework.scheduling.timer.ScheduledTimerTask){
        delay = 60000
        period = 60000
        timerTask = ref('doFooTimerTask')
    }
    
    timerFactory(org.springframework.scheduling.timer.TimerFactoryBean){
        scheduledTimerTasks = [ref('doFooScheduledTimerTask')]
    }   
}

The code above uses Grails' Spring DSL to define the necessary beans to implement the needed functionality. The first segment defines a MethodInvokingTimerTaskFactoryBean which sets up the service and the metod to be called. The next segment defines a ScheduledTimerTask which setups the initial delay and the period between calls. The third and last bean initializes the timer factory which is a TimerFactoryBean which is responsible for running each timer task at the specified intervals.

1 comment:

  1. You save my life!
    Quartz plugin failed with clusters...

    ReplyDelete