Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to place a recurring task in a Grails app?

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.

like image 794
C. Ross Avatar asked Dec 22 '22 18:12

C. Ross


2 Answers

I've never used it but the Grails Quartz plugin should let you do what you want.

like image 148
Jared Avatar answered Jan 07 '23 20:01

Jared


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).

like image 24
Ben Inkster Avatar answered Jan 07 '23 20:01

Ben Inkster