- For a scheduled job in java we have three main components JOB,TRIGGER,SCHEDULER.
- Quartz Scheduler is one of the API in java provides scheduling a job.
- The Library can be downloaded from :-
http://quartz-scheduler.org/downloads
- The required jar files are :-
quartz-2.1.6.jar,
quartz-all-2.1.6.jar,
quartz-commonj-2.1.6.jar,
slf4j-api-1.7.2.jar,
slf4j-simple-1.7.2.jar
Project Structure:-
Quartz Configuration:-
org.quartz.scheduler.instanceName = MyScheduler
org.quartz.threadPool.threadCount = 3
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
Quartz Job Class:-
package com.sandeep.quartz.scheduler;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
public class DemoJob implements Job{
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobKey jobKey = context.getJobDetail().getKey();
System.out.println("Hi This is a demo job "+jobKey);
}
}
Creating and Scheduling job:-
- This job will be called in every 3 seconds.
package com.sandeep.quartz.scheduler;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzSchedulerDemo {
public static void main(String[] args) {
JobDetail demoJob = newJob(DemoJob.class)
.build();
Trigger trigger = newTrigger()
.withIdentity("SandeepDemoTrigger")
.withSchedule(
simpleSchedule().withIntervalInSeconds(3)
.repeatForever()).build();
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched;
try {
sched = sf.getScheduler();
sched.scheduleJob(demoJob, trigger);
sched.start();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
Output:-
Hi This is a demo job DEFAULT.6da64b5bd2ee-a297d774-ea8a-4569-b70c-24f22706e15d
Hi This is a demo job DEFAULT.6da64b5bd2ee-a297d774-ea8a-4569-b70c-24f22706e15d
….