用Mave工程上手实践一下。
1.maven依赖
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
2.工程结构
一个MyJob类,一个main调用类
MyJob类
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.Date;
public class MyJob implements Job {
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("name: MyJob" + "time:" + new Date());
}
}
QuartzTest类
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzTest {
public static void main(String[] args){
try {
//定义一个任务
JobDetail jobDetail = JobBuilder
.newJob(MyJob.class)
.withIdentity("myJobName","myJobGroup")
.build();
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("myTriggerName","myTriigerGroup")
.withDescription("This is a Trigger !")
.withSchedule(SimpleScheduleBuilder
.simpleSchedule()
//每五秒重复一次
.withIntervalInSeconds(5)
.repeatForever())
.build();
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.scheduleJob(jobDetail,trigger);
scheduler.start();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
执行结果(任务内容是,立即执行,并每五秒重复一次,一直重复)
其中quartz集成了slf4j日志框架,在没有配置的时候会标红。