Grails中类似cron调度的建议:每小时运行一次方法

时间:2010-04-13 23:44:23

标签: grails

假设我想在Grails中每小时运行以下方法foo()

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

在Grails中设置类似cron的调度的最简单/推荐方法是什么?

2 个答案:

答案 0 :(得分:11)

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

  

添加Quartz作业调度功能......

     

从1.0-RC3开始,这个插件使用Quartz 2.1.x,不再使用Quartz 1.8.x.如果你想使用Terracotta 3.6+,这是一个可以使用的插件。这是因为另一个'quartz2'插件不使用Terracotta 3.6所需的JobDetailsImpl类。有关详细信息,请参阅https://jira.terracotta.org/jira/browse/QTZ-310

     

可以找到完整的文档here

答案 1 :(得分:3)

如果您不想添加其他插件依赖项,则可以使用JDK Timer类。只需将以下内容添加到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) 
}