Monday, February 20, 2012

Quartz Scheduler

OverView : Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java EE or Java SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that are programmed to fulfill the requirements of your application. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering

Needed Jar :
  • quartz-all-2.1.3
  • log4j-1.2.16
  • slf4j-log4j12-1.6.1
Smaple Code:

demo.java(main Class)
-------------------------

package test;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class demo {

    public static void main(String[] args) throws SchedulerException {
        try{
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
      
        scheduler.start();
      
         // define the job and tie it to our HelloJob class
        JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity("job1", "group1")
        .build();
      
        // Trigger the job to run now, and then every 5 seconds
          Trigger trigger = TriggerBuilder.newTrigger()
          .withIdentity("myTestTrigger", "myTestgroup")
          .startNow()
          .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                          .withIntervalInSeconds(5)
                          .repeatForever())          
          .build();
        
        // Tell quartz to schedule the job using our trigger
          scheduler.scheduleJob(job, trigger);

      
        //scheduler.shutdown();
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("Complete mPower");
    }

}

HelloJob .java(JobClass)
-------------------------

package test;

import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class HelloJob implements Job {

    public HelloJob() {
    }

    public void execute(JobExecutionContext context)
      throws JobExecutionException
    {
      System.err.println("Hello!  mPower Job is executing. Time : " + new Date());
    }
  }

Output:
--------------


 u can see job is exectuting after 5 sec. continuously...
 

1 comment:

Disqus for yogi's talk

comments powered by Disqus