A scheduler maintains job details and trigger details.
Scheduler is responsible to fire the job, when their scheduled time arrives.
How to create a
scheduler?
‘SchedulerFactory´interface is used to create a
scheduler. Once scheduler is created, it is in stand-by mode. You need to call
the start() method explicitly to activate the scheduler.
How to register a job
to the scheduler?
Use the scheduleJob method to register a job to the
scheduler.
Example
// Initiate a Schedule Factory
SchedulerFactory schedulerFactory = new
StdSchedulerFactory();
// Retrieve a scheduler from schedule factory
Scheduler scheduler = schedulerFactory.getScheduler();
// Start scheduler
scheduler.start();
How to identify a job
and triggers in a scheduler?
Every job, trigger has a name and group associated with
them. These are used to uniquely identify them within a single scheduler.
HelloJob.java
package com.sample.jobs; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class HelloJob implements Job { public void execute(JobExecutionContext jec) throws JobExecutionException { System.out.println("Hello!!!"); } }
QuartzSchedulerEx.java
package com.sample.app; import java.util.Date; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.impl.JobDetailImpl; import org.quartz.impl.StdSchedulerFactory; import org.quartz.impl.triggers.SimpleTriggerImpl; import com.sample.jobs.HelloJob; public class QuartzSchedulerEx { public static void main(String args[]) throws SchedulerException, InterruptedException { // Initiate a Schedule Factory SchedulerFactory schedulerFactory = new StdSchedulerFactory(); // Retrieve a scheduler from schedule factory Scheduler scheduler = schedulerFactory.getScheduler(); // Start scheduler scheduler.start(); JobDetailImpl helloJobDetails = new JobDetailImpl(); helloJobDetails.setName("Hello Job"); helloJobDetails.setJobClass(HelloJob.class); // Creating schedule time with trigger SimpleTriggerImpl trigger1 = new SimpleTriggerImpl(); trigger1.setStartTime(new Date(System.currentTimeMillis() + 500)); trigger1.setRepeatCount(-1); trigger1.setRepeatInterval(1000); trigger1.setName("First Trigger"); trigger1.setPriority(10); // Setting trigger 1 priority to 10 scheduler.scheduleJob(helloJobDetails, trigger1); } }
Output
Hello!!!
Hello!!!
Hello!!!
No comments:
Post a Comment