任务类
package org.gof.test;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class HelloJob implements Job {
private String hello;
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println(hello);
}
}
调度器
package org.gof.test;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
public class MySchedule {
private Scheduler scheduler;
public void start(){
try {
scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void addTask(JobDetail job,Trigger trigger){
try {
scheduler.scheduleJob(job, trigger);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
测试类
package org.gof.test
import org.quartz.CronScheduleBuilder
import org.quartz.JobBuilder
import org.quartz.JobDetail
import org.quartz.Scheduler
import org.quartz.SimpleScheduleBuilder
import org.quartz.Trigger
import org.quartz.TriggerBuilder
import org.quartz.impl.StdSchedulerFactory
public class Test {
public static void main(String[] args)throws Exception {
Trigger trigger1 = TriggerBuilder.newTrigger().withIdentity("triggerName1", "group1")
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()).build()
Trigger trigger2 = TriggerBuilder
.newTrigger()
.withIdentity("triggerName2", "group1")
.withSchedule(
CronScheduleBuilder.cronSchedule("0/2 * * * * ?"))
.build()
JobDetail job1 = JobBuilder.newJob(HelloJob.class).withIdentity("dummyJobName1", "group1").build()
job1.getJobDataMap().put("hello", "hello World")
JobDetail job2 = JobBuilder.newJob(HelloJob.class).withIdentity("dummyJobName2", "group1").build()
job2.getJobDataMap().put("hello", "hello quartz")
MySchedule ms = new MySchedule()
ms.start()
ms.addTask(job1, trigger1)
ms.addTask(job2, trigger2)
}
}
输出结果
hello World
hello quartz
hello World
hello quartz
hello World
hello quartz
hello World
hello quartz
hello World
hello quartz