Tuesday, May 22, 2012

Quartz Job Scheduler

//a better Groovy DSL example: https://gist.github.com/1505600
//Note: a simple timer implementation with runAfter(): http://mrhaki.blogspot.ca/2009/11/groovy-goodness-run-code-at-specified.html

@Grapes(
    @Grab(group='org.quartz-scheduler', module='quartz', version='2.1.5')
)
import org.quartz.*
import org.quartz.impl.*
import static org.quartz.JobBuilder.*
import static org.quartz.TriggerBuilder.*
import static org.quartz.SimpleScheduleBuilder.*

class HelloJob implements Job {
    public void execute(JobExecutionContext context) {
        println "Hello "+(new Date().getTime())
    }
}

try {
    // Grab the Scheduler instance from the Factory 
    Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler()

    // Start it!
    scheduler.start()

     JobDetail job = newJob(HelloJob)
         .withIdentity("myJob"+(new Date().getTime()), "group1")
         .build()
         
     Trigger trigger = newTrigger()
         .withIdentity(new TriggerKey("myTrigger"+(new Date().getTime()), "group1"))
         .withSchedule(simpleSchedule()
             .withIntervalInSeconds(5)
             .repeatForever())
         .startNow()
         .build()

    // Tell quartz to schedule the job using our trigger
    scheduler.scheduleJob(job, trigger)
    
    // Pause thread for 60 seconds
    Thread.sleep(60000)
    
    // End it!
    scheduler.shutdown()
}
catch (SchedulerException se) {
    se.printStackTrace()
}

4 comments:

  1. You cannot create an instance from the abstract interface 'org.quartz.Job'.

    ReplyDelete
  2. Thanks, I'll update it now with a bit better code.

    ReplyDelete
  3. Nice man. Worked perfectly now.
    Thanks for the example

    ReplyDelete
  4. Bài post của Bạn cũng hữu ích, cám ơn bạn đã share.
    Xem tại website : Thạch anh vụn

    ReplyDelete