SpringBoot2.0整合quartz发布定时任务


使用工具

  • IntelliJ IDEA 2018.1 x64
  • jdk8
  • SpringBoot 2.0

步骤

首先,先创建一个SpringBoot项目,在pom.xml里面添加依赖

1
2
3
4
5
<!--定时任务依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

然后,包名下面创建config目录,创建QuartzConfig.java类作为定时任务的配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Configuration
public class QuartzConfig {
@Bean
public JobDetail testDataJobDetail(){
return JobBuilder.newJob(TestQuartzJob.class)
.withIdentity("testDataJobDetail")
.storeDurably().build();
}

@Bean
public Trigger testDataTrigger(){
// 设置定时同步缓存数据
ScheduleBuilder schedBuilder =SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(1800).repeatForever();

return TriggerBuilder.newTrigger().forJob(testDataJobDetail())
.withIdentity("testDataTrigger")
.withSchedule(schedBuilder).build();
}
}

其中TestQuartzJob是定时任务类,withIntervalInSeconds是设置时间进行同步,以秒为单位,这里设置了1800秒,也就是30分钟。
接下来,开始创建定时任务类TestQuartzJob,便于区分,我们新建包名job用来专门存放定时任务类

1
2
3
4
5
6
7
8
9
10
public class TestQuartzJob extends QuartzJobBean {

private static final Logger logger =LoggerFactory.getLogger(TestQuartzJob.class);

@Override
protected void executeInternal(JobExecutionContext jobExecutionContext)
throws JobExecutionException {
logger.info("开始定时任务");
}
}

为了方便测试,我们把之前设定的1800秒换成5秒,启动之后观察控制台的日志

注意日志时间,的确是5秒一次,这样我们的定时任务也就完成了。

(PS:第一次自己写博客,写的不好请多指正,留下你的评论,一起探讨吧>_<)

-------------本文结束感谢您的阅读-------------