Quartz Scheduer Simple Trigger example using java



SimpleTrigger

SimpleTrigger should meet your scheduling needs if you need to have a job execute exactly once at a specific moment in time, or at a specific moment in time followed by repeats at a specific interval.

For example, if you want the trigger to fire at exactly 11:23:54 AM on January 13, 2015, or if you want it to fire at that time, and then fire five more times, every ten seconds.

With this description, you may not find it surprising to find that the properties of a SimpleTrigger include: a start-time, and end-time, a repeat count, and a repeat interval.

The repeat count can be zero, a positive integer, or the constant value SimpleTrigger.REPEAT_INDEFINITELY. The repeat interval property must be zero, or a positive long value, and represents a number of milliseconds. Note that a repeat interval of zero will cause ?repeat count? firings of the trigger to happen concurrently (or as close to concurrently as the scheduler can manage).


Program 

SimpleTriggerApp.java

package com.candidjava.quartz;

import java.util.Date;

import org.quartz.DateBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class SimpleTriggerApp {
	public static void main(String[] args) {

		try {

			SchedulerFactory sf = new StdSchedulerFactory();
			Scheduler scheduler = sf.getScheduler();

			JobDetail job = JobBuilder.newJob(Main.class)
					.withIdentity("dummyJobName", "group1").build();

			Date startTime = DateBuilder.nextGivenSecondDate(null, 10);

			// run 10 seconds only 4 times infinite loop
			SimpleTrigger simpletrigger = TriggerBuilder
					.newTrigger()
					.withIdentity("FourTimesTrigger", "group1")
					.startAt(startTime)
					// startNow()
					.withSchedule(SimpleScheduleBuilder.simpleSchedule()
					.withIntervalInSeconds(10)
					.withRepeatCount(4)).build();

							

			scheduler.start();
			scheduler.scheduleJob(job, simpletrigger);

			// scheduler.shutdown();

		} catch (SchedulerException se) {
			se.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

Main.java

package com.candidjava.quartz;

import java.util.Date;

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


public class Main implements Job
{
	public void execute(JobExecutionContext context) throws JobExecutionException 
	{
		
		System.out.println("Trigger Starts.."+new Date());	
		
	}
	
}

Output

Trigger Starts..Wed Jun 01 15:12:30 IST 2016

Trigger Starts..Wed Jun 01 15:12:40 IST 2016

Trigger Starts..Wed Jun 01 15:12:50 IST 2016

Trigger Starts..Wed Jun 01 15:13:00 IST 2016




Related Post

Comments


©candidjava.com