在這個(gè)例子中,我們將介紹如何通過(guò)Quartz API 多個(gè)作業(yè)。在Quartz調(diào)度框架中,每個(gè)作業(yè)將被連接到一個(gè)唯一的觸發(fā),并且由調(diào)度器運(yùn)行它。
P.S:在 Quartz 中,一個(gè)觸發(fā)器觸發(fā)多個(gè)作業(yè)是不可以的。
創(chuàng)建3個(gè)作業(yè),JobA,JobB和JobC。
package com.yiibai.quartz; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class JobA implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("Job A is runing //every 5 seconds "); } }
package com.yiibai.quartz; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class JobB implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("Job B is runing"); } }
package com.yiibai.quartz; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class JobC implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("Job C is runing"); } }
使用QuartzAPI聲明上述3個(gè)作業(yè),分配它們到特定觸發(fā)器并調(diào)度它。
package com.yiibai.quartz; import org.quartz.CronScheduleBuilder; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; public class CronTriggerExample { public static void main( String[] args ) throws Exception { JobKey jobKeyA = new JobKey("jobA", "group1"); JobDetail jobA = JobBuilder.newJob(JobA.class) .withIdentity(jobKeyA).build(); JobKey jobKeyB = new JobKey("jobB", "group1"); JobDetail jobB = JobBuilder.newJob(JobB.class) .withIdentity(jobKeyB).build(); JobKey jobKeyC = new JobKey("jobC", "group1"); JobDetail jobC = JobBuilder.newJob(JobC.class) .withIdentity(jobKeyC).build(); Trigger trigger1 = TriggerBuilder .newTrigger() .withIdentity("dummyTriggerName1", "group1") .withSchedule( CronScheduleBuilder.cronSchedule("0/5 * * * * ?")) .build(); Trigger trigger2 = TriggerBuilder .newTrigger() .withIdentity("dummyTriggerName2", "group1") .withSchedule( CronScheduleBuilder.cronSchedule("0/5 * * * * ?")) .build(); Trigger trigger3 = TriggerBuilder .newTrigger() .withIdentity("dummyTriggerName3", "group1") .withSchedule( CronScheduleBuilder.cronSchedule("0/5 * * * * ?")) .build(); Scheduler scheduler = new StdSchedulerFactory().getScheduler(); scheduler.start(); scheduler.scheduleJob(jobA, trigger1); scheduler.scheduleJob(jobB, trigger2); scheduler.scheduleJob(jobC, trigger3); } }
輸出結(jié)果如上:
Job A is runing //every 5 seconds Job B is runing Job C is runing Job A is runing //every 5 seconds Job B is runing Job C is runing