Removing Triggers and Rescheduling a Quartz 2 Job programatically

17 / Jul / 2012 by Puneet Behl 4 comments

In my recent project there was a use case to change repeat interval of job so that job runs after every 8 seconds instead of 1 second.

class TestJob {

    def concurrent = false

    static triggers = {
        simple repeatInterval: 1000l // execute job once in 1 sec
    }

    def execute() {
        println "executing job"
    }
}

Using

TestJob.schedule(8000l)

scheduled job to trigger at every 8 seconds but it did not remove existing trigger of running job after 1 second. Thanks to my colleagues Vivek and Ankur, we found following way to remove existing triggers and schedule job again:

       def quartzScheduler                // Inject the quartzScheduler bean
     def reScheduleJob = {
        // find jobKey of job
        def jobKey = grailsApplication.jobClasses.find {it.clazz == TestJob.class}.jobKey
        // get list of existing triggers
        def triggersList = quartzScheduler.getTriggersOfJob(jobKey)
        triggersList.each {
            quartzScheduler.unscheduleJob(it.key)  // remove all existing triggers
        }
    }

Now schedule job to trigger after every 8 seconds

TestJob.schedule(8000l)

It worked for us.Hope it will save your time too.

FOUND THIS USEFUL? SHARE IT

comments (4)

  1. Daniel

    This helped me out a bunch, the only thing I had to add was the “import org.quartz.impl.matchers.GroupMatcher”

    Reply
  2. Ben

    Thanks. This was useful, but it didn’t work exactly as written. I suppose the API may have changed in the last two years.

    Here’s what worked for me:
    def unscheduleJob(def jobName) {
    // Find jobKey of job.
    def jobKeys = quartzScheduler.getJobKeys(GroupMatcher.anyJobGroup())
    def jobKey = jobKeys.find {it.name.endsWith(jobName)}
    // Get list of existing triggers.
    def triggersList = quartzScheduler.getTriggersOfJob(jobKey)
    triggersList.each {
    quartzScheduler.unscheduleJob(it.key) // remove all existing triggers
    }
    }

    Reply

Leave a comment -