Quartz is an open-source job scheduling library, which can be integrated with any Java application. It can be used for scheduling few jobs to thousands of jobs at scale according to the requirement. It can be used for clustering as well as Java Transaction API.
If our application has to perform some tasks at certain moments, or if our system has to perform some recurring jobs, the Quartz is an ideal solution. An example of such a job is discussed below.
Process Workflow |
Schedule a Job to fire in a certain interval, that will execute some tasks which are inter-dependent, but do not form a dependency cycle. |
System Maintenance |
Schedule a job to backup database server at the end of the day (EOD). |
An example code is given below.
package com.t4b.demo.quartz;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class HelloJob implements Job {
public HelloJob() {
}
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("Hello World! - " + new Date());
}
}
package com.t4b.demo.quartz;
import static org.quartz.DateBuilder.evenMinuteDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import java.util.Date;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
public class SimpleExample {
public void run() throws Exception {
System.out.println("------- Initializing ----------------------");
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
System.out.println("------- Initialization Complete -----------");
Date runTime = evenMinuteDate(new Date());
System.out.println("------- Scheduling Job -------------------");
JobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").build();
Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runTime).build();
sched.scheduleJob(job, trigger);
System.out.println(job.getKey() + " will run at: " + runTime);
sched.start();
System.out.println("------- Started Scheduler -----------------");
System.out.println("------- Waiting 60 seconds... -------------");
try {
Thread.sleep(60L * 1000L);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("------- Shutting Down ---------------------");
sched.shutdown(true);
System.out.println("------- Shutdown Complete -----------------");
}
public static void main(String[] args) throws Exception {
SimpleExample simpleExample = new SimpleExample();
simpleExample.run();
}
}
Happy Exploring!
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.