Quartz的大名如雷贯耳,这里就不赘述,而且本文也不作为深入探讨,只是看完Quartz的官方文档后,下个简单示例,至少证明曾经花了点时间学习过,以备不时之需。

Quartz使用了SLF4J,所以至少你也知道如何配置日志,开发过程中最好把Quartz的日志打印出来,方便排查问题。先不详解直接上一个Demo.

项目结构如图:

Java调度框架Quartz简单示例-LMLPHP

log4j.properties

#log4j.logger.org.quartz=OFF
log4j.logger.org.quartz=INFO,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d{mm:ss,SSS} %M %m%n

HelloJob.java

package net.oseye;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException; public class HelloJob implements Job{ public void execute(JobExecutionContext arg0) throws JobExecutionException { System.out.println(arg0.getJobDetail().getKey().getName());
}
}

App.java

package net.oseye;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory; public class App {
public static void main(String[] args) {
JobDetail job = JobBuilder.newJob(HelloJob.class)
.withIdentity("job1", "group1")
.build(); SchedulerFactory sf = new StdSchedulerFactory();
try {
Scheduler sched = sf.getScheduler(); Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger1", "group1")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10)
.repeatForever())
.build();
sched.scheduleJob(job, trigger);
sched.start();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}

执行后输出

可以看出默认使用10个线程,使用的JobStor是RAM。

04-28 18:30