Recommendations for cron-like scheduling in Grails: run method once every hour
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?
Quartz plugin: http://grails.org/plugin/quartz
Adds Quartz job scheduling features...
Starting from 1.0-RC3, this plugin uses Quartz 2.1.x, and no longer uses Quartz 1.8.x. If you want to use Terracotta 3.6+, this is the plugin to use. This is because the other 'quartz2' plugin doesn't use JobDetailsImpl class, which Terracotta 3.6 requires. See https://jira.terracotta.org/jira/browse/QTZ-310 for more info...
Full documentation can be found here
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)
}
精彩评论