tags:

views:

82

answers:

2

Suppose I want to run the following method foo() once every hour in Grails:

class FooController {
  public static void foo() {
    // stuff that needs to be done once every hour (at *:00)
  }
}

What is the easiest/recommended way to set up such cron-like scheduling in Grails?

+9  A: 

Quartz plugin: http://grails.org/plugin/quartz

armandino
+1  A: 

If you don't want to add another plugin dependency, an alternative is to use the JDK Timer class. Simply add the following to Bootstrap.groovy

def init = { servletContext ->
    // The code for the task should go inside this closure
    def task = { println "executing task"} as TimerTask

    // Figure out when task should execute first
    def firstExecution = Calendar.instance

    def hour = firstExecution.get(Calendar.HOUR_OF_DAY)
    firstExecution.clearTime()
    firstExecution.set(Calendar.HOUR_OF_DAY, hour + 1)

    // Calculate interval between executions
    def oneHourInMs = 1000 * 60 * 60

    // Schedule the task
    new Timer().scheduleAtFixedRate(task, firstExecution.time, oneHourInMs) 
}
Don