Pages

Wednesday, March 4, 2015

Grails scheduled execution of some method aka job

In my project i needed a method to execute once per day, that did something to my database, or schedule a job. There is a plugin for this - quartz. Setting up took 5 minutes.

1) In build config add next line, then refresh dependencies:

compile ":quartz:1.0.2"

2) run command: grails create-job YourJobName

3) In your project grails-app/jobs folder the file will be created. In the execute() method put what needs to be executed, or a call to a service method, as i did.

4) Inside the static triggers add some trigger. There are several types of triggers, easy one, cron trigger and some other one. Easy trigger just triggers the execute method, for example, each 5 minutes. The cron trigger allows you to enter a cron expression to schedule the execute method.

static triggers = {
  cron  cronExpression: "00 00 00 * * ?"
  /**
  * cronExpression: "s m h D M W Y"
       *           | | | | | | `- Year [optional]
       *           | | | | | `- Day of Week, 1-7 or SUN-SAT, ?
       *               | | | | `- Month, 1-12 or JAN-DEC
       *               | | | `- Day of Month, 1-31, ?
       *               | | `- Hour, 0-23
       *               | `- Minute, 0-59
       *          `- Second, 0-59
  */

    }

The cron trigger above triggers the execute method every day at 00 hours, 00 minutes and 00 seconds. Not that if the expression would be * * 00 * * ?, then the job would be executed at 00 hours all the time, and will stop cycling the execute method when hours become 01.

Well, now when you do grails run-app the scheduling is turned on and you have a working scheduled job waiting for the specified time to be executed.

Oh, and in case something is unclear, check the documentation -> http://grails-plugins.github.io/grails-quartz/guide/introduction.html

No comments:

Post a Comment