Wednesday 29 October 2014

First Quartz Scheduling Application


There are two fundamental units in Quartz scheduling.
1.   Job
2.   Trigger
A job is an executable task that can be scheduled. A trigger provides a schedule for the job.

It is a two-step process to develop an application using Quartz scheduling package.

Step 1:  Create a Quartz job.
Quartz job can be created by implementing the org.quartz.job interface.
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class HelloWorld implements Job{
    public void execute(JobExecutionContext jec) throws JobExecutionException {
        System.out.println("Hello World");
    }
}

Step 2: Schedule the job
import java.util.Date;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.SimpleTriggerImpl;

public class QuartzSchedulerEx {
    public static void main(String args[]) throws SchedulerException{

        // Initiate a Schedule Factory
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        // Retrieve a scheduler from schedule factory
        Scheduler scheduler = schedulerFactory.getScheduler();

        //Creating JobDetailImpl and link to our Job class
  JobDetailImpl jobDetail = new JobDetailImpl();
  jobDetail.setName("First Job");
  jobDetail.setJobClass(HelloWorld.class);

        //Creating schedule time with trigger
  SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl();
  simpleTrigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
  simpleTrigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
  simpleTrigger.setRepeatInterval(3000);
  simpleTrigger.setName("FirstTrigger");

  //Start scheduler
  scheduler.start();
  scheduler.scheduleJob(jobDetail,simpleTrigger);

    }
}

Comments in the program are self-explanatory. When you run above program "Hello World" message is printed for every 3 seconds.

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment