定时调度集成 - Quartz
???????在日常项目运行中,我们总会有需求在某- -时间段周期性的执行某个动作。比如每天在某个时间段导出报表,或者每隔多久统计一次现在在线的用户量等。 ???????在Spring Boot中有Java自带的java.util.Timer类,也有强大的调度器Quartz,还有SpringBoot自带的Scheduled来实现。Scheduled 在Spring3.X引入,默认SpringBoot自带该功能,使用起来也很简单,在启动类级别添加@EnableScheduling注解即可引入定时任务环境。但遗憾的是Scheduled默认不支持分布式环境,这里主要讲解Quartz时钟调度框架与Spring Boot集成。
1、环境整合配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
2、源代码添加
2.1 定义job
在com.xxx下添加jobs 包,定义待执行job任务。实现Job接口,并且在execute 方法中实现自己的业务逻辑。
public class MyFirstJob implements Job {
private Logger logger = LoggerFactory.getLogger(MyFirstJob.class);
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("定时任务.....");
logger.info("当前时间:{}",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
2.2 构建调度配置类
创建JobDetail 实例并定义Trigger 注册到 scheduler ,启动 scheduler 开启调度
@Configuration
public class QuartzConfig {
@Bean
public JobDetail getJobDetail(){
return JobBuilder.newJob(MyFirstJob.class).storeDurably().build();
}
@Bean
public Trigger trigger01(){
SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(1)
.repeatForever();
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger01","group01")
.withSchedule(simpleScheduleBuilder)
.forJob(getJobDetail())
.build();
return trigger;
}
@Bean
public Trigger trigger02(){
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ? *");
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger02","group02")
.withSchedule(cronScheduleBuilder)
.forJob(getJobDetail())
.build();
return trigger;
}
}
2.3 启动Starter
查看控制台打印效果
|