最近项目要用到任务调度的相关知识,昨天信心满满的去官网学习,结果被坑个半死,我用的最新版的quartz,文档里说是兼容所有版本,但是代码连编译都报错,无奈只好从网上找资料,摸着石头过河总算有点眉目,在此分享,顺便记录。
Maven项目:
pom.xml引用如下: org.quartz-scheduler quartz 2.1.7 org.quartz-scheduler quartz-oracle 2.1.7 org.quartz-scheduler quartz-weblogic 2.1.7 org.quartz-scheduler quartz-jboss 2.1.7
相关类如下:
package test.quartz;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class SimpleJob implements Job
{
// ①实例Job接口方法 public void execute(JobExecutionContext context) throws JobExecutionException { // Say Hello to the World and display the date/time System.out.println("Hello World! - " + new Date());
}
}
package test.quartz;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
public class SimpleTriggerRunner{
public static void main(String[] args) throws Exception
{
SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
Scheduler sched = schedFact.getScheduler(); // define the job and tie it to our HelloJob class
JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("myJob", "group1").build(); // Trigger the job to run now, and then every 40 seconds
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTrigger", "group1").startNow().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()).build();
// Tell quartz to schedule the job using our trigger
sched.scheduleJob(job, trigger);
sched.start();
Thread.sleep(9L * 1000L);
sched.shutdown(true);
}
}
以上demo是最简单的入门例子,更多复杂的说明还是需要参考文档的说明。