Example of Cron Trigger

In this section we are just providing you a Cron Trigger example and by this, you can better understand the working of cron trigger.

Example of Cron Trigger

Example of Cron Trigger

     

In this section we are just providing you a Cron Trigger example and by this, you can better understand the working of cron trigger. 

Description of Program

In this following program we are just creating a Quartz application with the help of cron trigger. For this, we have to make two classes one is job class (CronJob.java) that is implementation of Job interface and second one is scheduler class. In scheduler class (CronSchedule.java), firstly we need the object of scheduler and for this we have to instantiate the SchedulerFactory and invoke its getScheduler() method. After getting the scheduler we require to instantiate the JobDetail object with the attributes like job name, group name and the job class name. Now we used Cron Trigger to firing the job repetitively after the specified time. After doing all these things we get the simple message like "Welcome to RoseIndia.net" and date specified intervals.

Description of Code

CronTrigger("cronTrigger","group2","0 0/1 * * * ?");

By the above constructor we just create the CronTrigger object with the trigger name, group name and the cron expression. Cron Expression are used to configuring the instance of Cron-Trigger. And this corn expression are used to just execute the job after one minute indefinitely.

 Here is the code of Job Class (CronJob.class) :

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.*;
public class CronJob implements Job {
  public void execute(JobExecutionContext arg0throws JobExecutionException {
  System.out.println("Welcome to RoseIndia.net  :"+new Date());
  }
}

Download this code

 Here is the code of Schedule Class (CronSchedule.class) :

import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.JobDetail;
public class CronSchedule {
  public CronSchedule ()throws Exception {
  SchedulerFactory sf=new StdSchedulerFactory();
  Scheduler sched=sf.getScheduler();
  JobDetail jd=new JobDetail("job1","group1",CronJob.class);
  CronTrigger ct=new CronTrigger("cronTrigger","group2","0 0/1 * * * ?");
  sched.scheduleJob(jd,ct);
  sched.start();
 }
  public static void main(String args[]){
  try{  
  new CronSchedule();
  }catch(Exception e){}
  }
}

Download this code

Output of the program :

log4j:WARN No appenders could be found for logger (org.quartz.simpl.SimpleThreadPool).

log4j:WARN Please initialize the log4j system properly.

Welcome to RoseIndia.net :Fri Feb 23 15:17:00 GMT+05:30 2007

Welcome to RoseIndia.net :Fri Feb 23 15:18:00 GMT+05:30 2007

Welcome to RoseIndia.net :Fri Feb 23 15:19:00 GMT+05:30 2007