SpringBoot:实现定时任务
一、定时任务实现的几种方式:
Timer
这是java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务。使用这种方式可以让你的程序按照某一个频度执行,但不能在指定时间运行。一般用的较少。
ScheduledExecutorService
也jdk自带的一个类;是基于线程池设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去执行,也就是说,任务是并发执行,互不影响。
Spring Task
Spring3.0以后自带的task,可以将它看成一个轻量级的Quartz,而且使用起来比Quartz简单许多。
Quartz
这是一个功能比较强大的的调度器,可以让你的程序在指定时间执行,也可以按照某一个频度执行,配置起来稍显复杂。
二、基于SpringBoot的定时任务
使用SpringBoot 自带的定时任务,只需要添加相应的注解就可以实现
2.1 导入SpringBoot启动包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
2.2 启动类启用定时
在启动类上面加上@EnableScheduling即可开启定时
@SpringBootApplication
@EnableScheduling // 开启定时
public class SpringBootDemoTimeTaskApplication {
private static final Logger logger = LoggerFactory.getLogger(SpringBootDemoTimeTaskApplication.class);
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoTimeTaskApplication.class);
logger.info("SpringBootDemoTimeTaskApplication start!");
}
}
2.3 创建定时任务实现类SchedulerTask
@Component
public class SchedulerTask {
private static final Logger logger = LoggerFactory.getLogger(SchedulerTask.class);
/**
* @Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行
* @Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行
* @Scheduled(initialDelay=1000, fixedRate=6000) :第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次
* @Scheduled(cron=""):详见cron表达式http://www.pppet.net/
*/
@Scheduled(fixedRate = 5000)
public void scheduled1() {
logger.info("=====>>>>>使用fixedRate执行定时任务");
}
@Scheduled(fixedDelay = 10000)
public void scheduled2() {
logger.info("=====>>>>>使用fixedDelay执行定时任务");
}
@Scheduled(cron="*/6 * * * * ?")
private void scheduled3(){
logger.info("使用cron执行定时任务");
}
}
运行结果:
2019-03-09 17:33:05.681 INFO 7752 --- [ main] c.v.t.SpringBootDemoTimeTaskApplication : SpringBootDemoTimeTaskApplication start!
2019-03-09 17:33:06.002 INFO 7752 --- [ scheduling-1] cn.van.task.service.SchedulerTask : 使用cron执行定时任务
2019-03-09 17:33:10.680 INFO 7752 --- [ scheduling-1] cn.van.task.service.SchedulerTask : =====>>>>>使用fixedRate执行定时任务
2019-03-09 17:33:12.003 INFO 7752 --- [ scheduling-1] cn.van.task.service.SchedulerTask : 使用cron执行定时任务
2019-03-09 17:33:15.676 INFO 7752 --- [ scheduling-1] cn.van.task.service.SchedulerTask : =====>>>>>使用fixedRate执行定时任务
2019-03-09 17:33:15.676 INFO 7752 --- [ scheduling-1] cn.van.task.service.SchedulerTask : =====>>>>>使用fixedDelay执行定时任务
2019-03-09 17:33:18.002 INFO 7752 --- [ scheduling-1] cn.van.task.service.SchedulerTask : 使用cron执行定时任务
2019-03-09 17:33:20.677 INFO 7752 --- [ scheduling-1] cn.van.task.service.SchedulerTask : =====>>>>>使用fixedRate执行定时任务
2019-03-09 17:33:24.002 INFO 7752 --- [ scheduling-1] cn.van.task.service.SchedulerTask : 使用cron执行定时任务
2019-03-09 17:33:25.680 INFO 7752 --- [ scheduling-1] cn.van.task.service.SchedulerTask : =====>>>>>使用fixedRate执行定时任务
2019-03-09 17:33:25.681 INFO 7752 --- [ scheduling-1] cn.van.task.service.SchedulerTask : =====>>>>>使用fixedDelay执行定时任务
2019-03-09 17:33:30.005 INFO 7752 --- [ scheduling-1] cn.van.task.service.SchedulerTask : 使用cron执行定时任务
2019-03-09 17:33:30.680 INFO 7752 --- [ scheduling-1] cn.van.task.service.SchedulerTask : =====>>>>>使用fixedRate执行定时任务
2019-03-09 17:33:35.680 INFO 7752 --- [ scheduling-1] cn.van.task.service.SchedulerTask : =====>>>>>使用fixedRate执行定时任务
2019-03-09 17:33:35.682 INFO 7752 --- [ scheduling-1] cn.van.task.service.SchedulerTask : =====>>>>>使用fixedDelay执行定时任务
2.4 执行时间的配置
在上面的定时任务中,我们在方法上使用@Scheduled注解来设置任务的执行时间,并且使用三种属性配置方式:
- fixedRate:定义一个按一定频率执行的定时任务
- fixedDelay:定义一个按一定频率执行的定时任务,与上面不同的是,改属性可以配合initialDelay, 定义该任务延迟执行时间。
- cron:通过表达式来配置任务执行时间--在线cron表达式生成器
三、多线程执行定时任务
SpringBoot定时任务默认单线程,可以看到三个定时任务都已经执行,并且使同一个线程中(
scheduling-1)串行执行,如果只有一个定时任务,这样做肯定没问题,当定时任务增多,如果一个任务卡死,会导致其他任务也无法执行。
3.1 多线程配置类 AsyncConfig.class
@Configuration // 表明该类是一个配置类
@EnableAsync // 开启异步事件的支持
public class AsyncConfig {
@Value("${myProps.corePoolSize}")
private int corePoolSize;
@Value("${myProps.maxPoolSize}")
private int maxPoolSize;
@Value("${myProps.queueCapacity}")
private int queueCapacity;
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.initialize();
return executor;
}
}
3.2 配置文件application.yml中添加多线程配置
myProps:
corePoolSize: 10
maxPoolSize: 100
queueCapacity: 10
3.3 在定时任务的类或者方法上添加@Async
此时,可让每一个任务都是在不同的线程中,启动项目,日志打印如下:
2019-03-11 15:16:54.855 INFO 10782 --- [ main] c.v.t.SpringBootDemoTimeTaskApplication : SpringBootDemoTimeTaskApplication start!
2019-03-11 15:16:55.015 INFO 10782 --- [ taskExecutor-1] cn.van.task.service.SchedulerTask : =====>>>>>使用cron执行定时任务-1
2019-03-11 15:17:00.002 INFO 10782 --- [ taskExecutor-2] cn.van.task.service.SchedulerTask : =====>>>>>使用cron执行定时任务-2
2019-03-11 15:17:00.002 INFO 10782 --- [ taskExecutor-3] cn.van.task.service.SchedulerTask : =====>>>>>使用cron执行定时任务-1
2019-03-11 15:17:05.003 INFO 10782 --- [ taskExecutor-4] cn.van.task.service.SchedulerTask : =====>>>>>使用cron执行定时任务-1
2019-03-11 15:17:06.005 INFO 10782 --- [ taskExecutor-5] cn.van.task.service.SchedulerTask : =====>>>>>使用cron执行定时任务-2
2019-03-11 15:17:10.004 INFO 10782 --- [ taskExecutor-6] cn.van.task.service.SchedulerTask : =====>>>>>使用cron执行定时任务-1
2019-03-11 15:17:12.005 INFO 10782 --- [ taskExecutor-7] cn.van.task.service.SchedulerTask : =====>>>>>使用cron执行定时任务-2
2019-03-11 15:17:15.006 INFO 10782 --- [ taskExecutor-8] cn.van.task.service.SchedulerTask : =====>>>>>使用cron执行定时任务-1
2019-03-11 15:17:18.004 INFO 10782 --- [ taskExecutor-9] cn.van.task.service.SchedulerTask : =====>>>>>使用cron执行定时任务-2
2019-03-11 15:17:20.004 INFO 10782 --- [taskExecutor-10] cn.van.task.service.SchedulerTask : =====>>>>>使用cron执行定时任务-1
日志打印证明了我的预测,至此,多线程中执行定时任务完毕!
四、源码及其延伸
https://github.com/vanDusty/SpringBoot-Home/tree/master/springboot-demo-list/task-demo
SpringBoot:实现定时任务的更多相关文章
- 玩转SpringBoot之定时任务详解
序言 使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式: 一.基于注解(@Scheduled) 二.基于接口(SchedulingConfigurer) 前者相信大家都很熟悉, ...
- SpringBoot 配置定时任务
SpringBoot启用定时任务,其内部集成了成熟的框架,因此我们可以很简单的使用它. 开启定时任务 @SpringBootApplication //设置扫描的组件的包 @ComponentScan ...
- SpringBoot - 添加定时任务
SpringBoot 添加定时任务 EXample1: import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spri ...
- springboot之定时任务
定时线程 说到定时任务,通常会想到JDK自带的定时线程来执行,定时任务. 回顾一下定时线程池. public static ScheduledExecutorService newScheduledT ...
- SpringBoot整合定时任务和异步任务处理 3节课
1.SpringBoot定时任务schedule讲解 定时任务应用场景: 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类 ...
- 十三、springboot集成定时任务(Scheduling Tasks)
定时任务(Scheduling Tasks) 在springboot创建定时任务比较简单,只需2步: 1.在程序的入口加上@EnableScheduling注解. 2.在定时方法上加@Schedule ...
- SpringBoot创建定时任务
之前总结过spring+quartz实现定时任务的整合http://www.cnblogs.com/gdpuzxs/p/6663725.html,而springboot创建定时任务则是相当简单. (1 ...
- springboot开启定时任务 添加定时任务 推送
最近在自学Java的springboot框架,要用到定时推送消息.参考了网上的教程,自己调试,终于调好了.下面将网上的教程归纳下,总结复习下. springboot开启定时任务 在SpringBo ...
- (入门SpringBoot)SpringBoot结合定时任务task(十)
SpringBoot整合定时任务task 使用注解EnableScheduling在启动类上. 定义@Component作为组件被容器扫描. 表达式生成地址:http://cron.qqe2.com ...
- SpringBoot整合定时任务和异步任务处理
SpringBoot定时任务schedule讲解 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类 timer:配置比较麻烦,时间延后问题, ...
随机推荐
- 数据库系统概念:JDBC
import java.sql.*; public class DataBase { public static void main() { } } /* 5.1.1 JDBC */ class JD ...
- OnCommandStateChange 不响应
原因是我把原先的OnCommandStateChange( long nCommand, BOOL bEnable )大BOOL改成了小bool,回调不认识了.
- 利用百度AI OCR图片识别,Java实现PDF中的图片转换成文字
序言:我们在读一些PDF版书籍的时候,如果PDF中不是图片,做起读书笔记的还好:如果PDF中的是图片的话,根本无法编辑,做起笔记来,还是很痛苦的.我是遇到过了.我们搞技术的,当然得自己学着解决现在的痛 ...
- Yarn工作机制
概述 (0)Mr 程序提交到客户端所在的节点. (1)Yarnrunner 向 Resourcemanager 申请一个 Application. (2)rm将该应用程序的资源路径和Applicati ...
- spring中获取容器中的Bean为什么前转成接口而不是实现类
简单介绍一下上下文,userService是服务层接口有一个save方法,userServiceImpl是该接口的实现类重写了save方法. applicationContext.xml如图: 后台代 ...
- PHP与ECMAScript_3_常用字符串函数
PHP ECMAScript 长度 strlen($str) str.length 查找类 $str[n] ...
- java往文本文件中写入信息并修改
题目要求: 1.可以往一个文本文档中写入员工信息:name,id和详情 2.可以更改name package FanCQ.Xue.practice; import java.io.*;import j ...
- git基础学习
1.git是什么 内容寻址文件系统,分布式版本控制系统 2.git作用 开发过程中的版本控制 3.git基础命令 克隆git仓库---clone:git clone 仓库url 选分支---check ...
- 【Java】Caused by: com.ibatis.sqlmap.client.SqlMapException: There is no statement named *** in this SqlMap.
如题: 可能原因: 在xxx.xml文件中有两个标签的id命名相同: DAO实现类方法中没有写对应xxx.xml的id名称: 实体映射文件xxx.xml未加入到sqlMap-Config.xml文件中 ...
- 03-Django模型类
ORM框架:对象-关系-映射 将面向对象语言程序中的对象自动持久化到关系数据库中.本质就是将数据从一种形式转换到另外一种形式O表示Object 对象类R表示Relations 关系,关系数据库中的表M ...