前言
定时任务是经常遇到的,主要有单机定时和分布式定时。今天简单总结一下写的几个小例子。之后再总结quatz的原理,源码,其他的定时调度器等。
核心组件
- scheduler调度器
- job 任务
- trigger 触发器
使用单纯的quatz包
- pom
<!--引入quartz-->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.1</version>
</dependency>
- job类
public class HelloJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("Hello Time " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss", Locale.CHINESE)));
}
}
- 主要类
public class LessonTwo {
public void run() throws Exception{
//创建调度器
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
//创建job
JobDetail jobDetail = JobBuilder.newJob(HelloJob.class).withIdentity("job2","group2").build();
//创建trigger
// Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger2","group2").startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.MINUTE)).build();
SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger().withIdentity("trigger2","group2").startAt(DateBuilder.nextGivenSecondDate(null,1)).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).withRepeatCount(3)).build();
//组装调度器
scheduler.scheduleJob(jobDetail,trigger);
//打印
System.out.println("schduler says " + jobDetail.getKey() + " will run at" + trigger.getStartTime() + "interval " + trigger.getRepeatInterval()+ "repeatCount : "+ trigger.getRepeatCount());
//调度器开始
scheduler.start();
//调度器关闭
scheduler.shutdown();
}
}
trigger中可以定义什么时候触发,隔多长时间触发一次,一共触发几次。
使用quatz和spring继承的jar包
- pom
<!--quartz需要 该tx jar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
单机版
- 配置文件
<!--有基类的定时任务配置-->
<!--job配置-->