Quartz is one of the technology with can be used for scheduling jobs i.e to run or execute something are certain specific time.
Many technology use Quartz implictly for job scheduling, so the chances are very high that you have written a job scheduling program and implicitly used Quartz.
Here I am going to explain how to use Quartz with Java.
Quartz scheduling has two part :
1) The job to be performed2) The schedule when it wll be performed.Creaing the Job:
Creating a job which you want to execute. For this you have to create a class which implements
Job interface from Quartz.
Job interface from Quartz.
public class SchedulerJob implements Job {
// you have to override this method and write the code which act as Job you want to excute .
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
// my job is to print hello world message
// you job may be to sftp some files to server or to generate some reports etc.
System.out.println("Hello World");
}
}
Part two, creating a Schedule for this job.
public class SchedulerJobImpl {
public void scheduleJob(){
JobKey jobKey = new JobKey("RouteSchedulerJob", "RouteSchedulerGroup");
// Creating Job and link to our Job class JobDetail job = JobBuilder.newJob(SchedulerJob.class).withIdentity(jobKey).build();
// Creating cron schedule time with trigger
Trigger trigger = newTrigger().withIdentity("RouteScheduler")
.withIdentity("RouteSchedulerTrigger", "RouteSchedulerGroup")
.withSchedule(cronSchedule("0 0/10 * ? * *")).build(); // adding the cron shedule
// Creating scheduler factory and scheduler
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched;
try {
sched = sf.getScheduler();
sched.scheduleJob(job, trigger); // adding job and trigger to schedule
sched.start(); // starting the schedule
} catch (SchedulerException e) {
log.error("Error occurred while starting the Quartz Cron Job for Scheduling the Job.");
e.printStackTrace();
log.error("Exiting .......");
System.exit(1);
}
}
}
Now final class to start and test
Applicaiton.java
public class Application {
public static void main (String [] args){
SchedulerJobImpl schedulerJobImpl = new SchedulerJobImpl();
schedulerJobImp.scheduleJob(); // this is do the job . That is it ,now your job is scheduled
//to run at time defined.
}
}
No comments:
Post a Comment