I'm learning grails, and I would like to include a recurring task that fires every five seconds while my app is running, and should have access to my domain objects and such. What is the proper way to accomplish this in Grails?
I considered starting a Timer in BootStrap.groovy
, but that would get disposed and kill the timer.
I've never used it but the Grails Quartz plugin should let you do what you want.
Quartz (http://grails.org/plugin/quartz) lets you define recurring tasks in much the same way as a CRON task would run on a single server.
You can install it in your project like this:
grails install-plugin quartz
Once it's installed, you can create a new job with:
grails create-job
Then you can schedule it like so:
class MyJob {
static triggers = {
simple name: 'mySimpleTrigger', startDelay: 60000, repeatInterval: 1000
}
def group = "MyGroup"
def execute(){
print "Job run!"
}
}
If you prefer the CRON formatting, you can schedule your trigger using a similar format:
static triggers = {
cron name: 'myTrigger', cronExpression: "0 0 6 * * ?"
}
However, since the grails app could be deployed across several servers (QA, staging, deploy, load balancer ...) the quartz plugin lets the specific process run regardless of which server it's deployed on.
One thing to keep an eye on is that the server clocks are synchronized - otherwise you could end up with some strange functionality (particularly if several servers share the same database).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With