Saturday, 3 August 2013

Quartz Scheduler , scheduler example in java


Quartz-Scheduler is a open source job scheduling service that can be integrated with, or used along side virtually any Java application - from the smallest stand-alone application to the largest e-commerce system.


Quartz is in use by many tens of thousands of entities, many of whom have directly embedded Quartz in their own custom applications, and others who are using products that already have Quartz embedded within them.

To know more visit :- Quartz Scheduler Enterprise Job Scheduler

if you need to implement Scheduler in your application Quartz can be downloaded here:- quartz.jar
add in java build path or lib folder.

Here is sample of Quartz process :-

Services.java
package com.javastoreroom.mytestapp;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class Services implements Job {
 
 /**
  * @see Job interface to be implemented by classes which represent  'job' to be performed. 
  */

 private static final Logger LOGGER =  Logger.getLogger(Services.class);
 public static void main(String args[]) {
  try {
   new ServiceThread();
  } catch (Exception e) {
  }
 }

 /**
  * @see execute Called by the Scheduler when a Trigger fires that is associated with the Job. 
  */
 
 @Override
 public void execute(JobExecutionContext arg0) throws JobExecutionException {
  new Services().add();
 }

 private void add() {
  int a = (int) (Math.random() * 50 ) , b = 10 , c = 0;
  c = a + b;
  LOGGER.info(" inside checking sum of two number ----->>> " + c);
 }
}


ServiceThread.java

package com.javastoreroom.mytestapp;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;


public class ServiceThread {


 public ServiceThread() throws Exception {

  SchedulerFactory sf = new StdSchedulerFactory(); // Before you can use the scheduler, it needs to be instantiated using  SchedulerFactory.
 
  Scheduler sched = sf.getScheduler(); // Scheduler interface can be used add, remove, and list Jobs and Triggers, and perform other scheduling- related operations.
  
  JobDetail jd = new JobDetail("job1", "group1", Services.class); // JobDetail object is created by the Quartz client (program) at the time the Job is added to the scheduler
  
  CronTrigger ct = new CronTrigger("cronTrigger", "group2","0 0/1 * * * ?"); // Cron Triggers -> firing job schedule that recurs based on calendar-like notions (HH:mm :ss . yyyy-MM-dd etc ... )
  
  sched.scheduleJob(jd, ct);
  sched.start(); 
 }


}


After running Services.java following result shown . CronTrigger expression (0 0/1 * * * ?) create a trigger that simply fires every 1 minutes -


Done :)