Job Scheduling (Quartz)

Last updated by admin 4 years ago

Scheduling Jobs

As of v 0.5.5-SNAPSHOT all Quartz related code was moved from Grails core to Quartz plugin. You should install this plugin to use job scheduling with 0.5.5 and greater versions of Grails.

Overview

Grails allows you to schedule jobs to be executed using a specified interval or cron expression. The underlying system uses the Quartz Enterprise Job Scheduler configured via Spring, but is made simpler by the coding by convention paradigm.

Scheduling Jobs

To create a new job run the "grails create-job" command and enter the name of the job. Grails will create a new job and place it in the "grails-app/jobs" directory:

class MyJob {
  def startDelay = 60000
  def timeout = 1000

def group = "MyGroup"

def execute(){ print "Job run!" } }


The above example will wait for 1 minute and after that will call the 'execute' method every second. The 'timeout' and 'startDelay' properties are specified in milliseconds and must have Integer or Long type. If these properties are not specified default values are applied (1 minute for 'timeout' property and 30 seconds for 'startDelay' property). It isn't recommended to set 'startDelay' property value lesser than 30 seconds since your application needs to fully startup before executing jobs. Jobs can optionally be placed in different groups. {color:#ff0000}Important: in earlier versions of Grails (before 0.5) 'startDelay' and 'timeout' properties must be defined as Strings and default values are 1 minute for 'timeout' and 0 seconds for 'startDelay'{color}

Scheduling a Cron Job

Jobs can be scheduled using a cron expression. For those unfamiliar with "cron", this means being able to create a firing schedule such as: "At 8:00am every Monday through Friday" or "At 1:30am every last Friday of the month". (See the API docs for the CronTrigger class in Quartz for more info on cron expressions):

class MyJob  {
 def cronExpression = "0 0 6 * * ?"

def group = "MyGroup"

def execute(){ print "Job run!" } }


Dependency Injection and Jobs

Jobs are configured for auto-wiring by name thus properties can be injected into them. To get hold of the data source you can do:

def javax.sql.DataSource dataSource

Or a service class:
def MyService myService

The Grails application context is configured using convention so most types can be injected simply by using their property name representation (ie the first letter being lower case in the majority of cases).

Hibernate Sessions and Jobs

_(Since 0.5)_ Jobs are configured by default to have Hibernate Session bounded to thread each time job is executed. This is required if you are using Hibernate code which requires open session (such as lazy loading of collections) or working with domain objects with unique persistent constraint (it uses Hibernate Session behind the scene). If you want to override this behavior (rarely useful) you can use 'sessionRequired' property:

def sessionRequired = false