Quartz Scheduer Cron Trigger example using java



CronTrigger

CronTrigger is often more useful than SimpleTrigger, if you need a job-firing schedule that recurs based on calendar-like notions, rather than on the exactly specified intervals of SimpleTrigger.

With CronTrigger, you can specify firing-schedules such as every Friday at noon, or every weekday and 9:30 am, or even every 5 minutes between 9:00 am and 10:00 am on every Monday, Wednesday and Friday during January.


Program

CronTriggerApp.java

package com.candidjava.quartz;

import java.util.Date;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
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.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class CronTriggerApp {
	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 every 20 seconds infinite loop
			CronTrigger crontrigger = TriggerBuilder
					.newTrigger()
					.withIdentity("TwentySec", "group1")
					.startAt(startTime)
					// startNow()
					.withSchedule(CronScheduleBuilder.cronSchedule("0/20 * * * * ?"))
					.build();

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

			// 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:22:40 IST 2016

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

Trigger Starts..Wed Jun 01 15:23:20 IST 2016

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

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

Trigger Starts..Wed Jun 01 15:24:20 IST 2016

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

                            -

                            -



Related Post

Comments


©candidjava.com