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.

4 comments:

  1. Very helpful post. Thank you!

    ReplyDelete
  2. You save my life!
    Quartz plugin failed with clusters...

    ReplyDelete
  3. The effectiveness of IEEE Project Domains depends very much on the situation in which they are applied. In order to further improve IEEE Final Year Project Domains practices we need to explicitly describe and utilise our knowledge about software domains of software engineering Final Year Project Domains for CSE technologies. This paper suggests a modelling formalism for supporting systematic reuse of software engineering technologies during planning of software projects and improvement programmes in Final Year Project Centers in Chennai.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

    ReplyDelete