Search code examples
grailsgroovyquartz-scheduler

Figure out which Quartz trigger triggered job


Is there a way to tell which trigger is the one the kicked the job off? I've got a Grails app and I'm using the quartz plugin to schedule some jobs, but I'd like to be able to do just a bit different things depending on which trigger kicked off the job...

class MyJob {

  static triggers = {
     cron name: 'noonTrigger', cronExpression: '0 0 12 * * ? *'//12:00 PM every day
     cron name: 'twoPMTrigger', cronExpression: '0 0 14 * * ? *'//2:00 PM every day
  }

  def execute(){
     if(noonTrigger)
        ...
     else if(twoPMTrigger)
        ...
     else
        ...//kicked off from controller
  }
}

Is there a way to tell in the execute which trigger kicked this off? Or maybe even a way to say this job wasn't kicked off by a trigger but was kicked off from some controller code or something like that?

EDIT: Based off of Joshua Moore's info, the code looks like this:

def execute(context){ 
  if(context.trigger.key.name == 'noonTrigger'){
    ...
  }...
  ...
}

Works like a champ. From a controller it seems the name is randomly(?) generated but this still works fine as well:

class MyController{
  def myMethod(){
    MyJob.triggerNow([:])
  }
}

Solution

  • The Grails Quartz plugin allows you to define your execute method with a single parameter for the JobExecutionContext (e.g. def execute(context)). From the JobExecutionContext you can use getTrigger() to find the trigger used to fire the job. Take a look at the API docs for JobExecutionContext for more information.