一、定时任务实现的几种方式:

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注解来设置任务的执行时间,并且使用三种属性配置方式:

  1. fixedRate:定义一个按一定频率执行的定时任务
  2. fixedDelay:定义一个按一定频率执行的定时任务,与上面不同的是,改属性可以配合initialDelay, 定义该任务延迟执行时间。
  3. 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:实现定时任务的更多相关文章

  1. 玩转SpringBoot之定时任务详解

    序言 使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式: 一.基于注解(@Scheduled) 二.基于接口(SchedulingConfigurer) 前者相信大家都很熟悉, ...

  2. SpringBoot 配置定时任务

    SpringBoot启用定时任务,其内部集成了成熟的框架,因此我们可以很简单的使用它. 开启定时任务 @SpringBootApplication //设置扫描的组件的包 @ComponentScan ...

  3. SpringBoot - 添加定时任务

    SpringBoot 添加定时任务 EXample1: import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spri ...

  4. springboot之定时任务

    定时线程 说到定时任务,通常会想到JDK自带的定时线程来执行,定时任务. 回顾一下定时线程池. public static ScheduledExecutorService newScheduledT ...

  5. SpringBoot整合定时任务和异步任务处理 3节课

    1.SpringBoot定时任务schedule讲解   定时任务应用场景: 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类        ...

  6. 十三、springboot集成定时任务(Scheduling Tasks)

    定时任务(Scheduling Tasks) 在springboot创建定时任务比较简单,只需2步: 1.在程序的入口加上@EnableScheduling注解. 2.在定时方法上加@Schedule ...

  7. SpringBoot创建定时任务

    之前总结过spring+quartz实现定时任务的整合http://www.cnblogs.com/gdpuzxs/p/6663725.html,而springboot创建定时任务则是相当简单. (1 ...

  8. springboot开启定时任务 添加定时任务 推送

    最近在自学Java的springboot框架,要用到定时推送消息.参考了网上的教程,自己调试,终于调好了.下面将网上的教程归纳下,总结复习下.  springboot开启定时任务  在SpringBo ...

  9. (入门SpringBoot)SpringBoot结合定时任务task(十)

    SpringBoot整合定时任务task 使用注解EnableScheduling在启动类上. 定义@Component作为组件被容器扫描. 表达式生成地址:http://cron.qqe2.com ...

  10. SpringBoot整合定时任务和异步任务处理

    SpringBoot定时任务schedule讲解 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类 timer:配置比较麻烦,时间延后问题, ...

随机推荐

  1. VUE+element tree 实现权限管理

    先写个标题~ ~,后续有空在写 具体功能: 1. 获取所有角色权限列表展示,点击进行编辑,编辑用terr树形结构显示页面结构 2.提交的数据格式(页面名称,角色ID,父节点ID,子节点ID) 3.后面 ...

  2. AT649 自由研究

    这道题有些水... 我们观察到,这是一道彻底离线的题目,连输入也没有,我们可以发现1<=n<=401<=n<=401<=n<=40 于是,我们就可以考虑n=1n=1 ...

  3. 个人永久性免费-Excel催化剂插件功能修复与更新汇总篇之九

    第11波-快速批量插入图片并保护纵横比不变 原文链接:https://www.jianshu.com/p/9a3d9aa7ba7e 修复了插入图片有纵向的图片时,插入后还是显示横向的情况. 第83波- ...

  4. 个人永久性免费-Excel催化剂功能第29波-追加中国特色的中文相关自定义函数

    中文世界里,有那么几个需求在原生Excel里没提供,例如财务部的数字转大写金额,文字转拼音等,在其他插件里,大部分是以功能区菜单按钮的方式提供.Excel催化剂认为,最佳的使用方式乃是自定义函数的方式 ...

  5. TCP概述\三次握手四次挥手\报文首部,常用熟知端口号

    06.26自我总结 1.TCP概述 TCP把连接作为最基本的对象,每一条TCP连接都有两个端点,这种端点我们叫作套接字(socket),它的定义为端口号拼接到IP地址即构成了套接字,例如,若IP地址为 ...

  6. SpringBoot系列——@Async优雅的异步调用

    前言 众所周知,java的代码是同步顺序执行,当我们需要执行异步操作时我们需要创建一个新线程去执行,以往我们是这样操作的: /** * 任务类 */ class Task implements Run ...

  7. MySql(Windows)

    百度云:链接:http://pan.baidu.com/s/1nvlSzMh      密码:o1cw 官网下载网址:http://dev.mysql.com/downloads/mysql/

  8. 必懂的webpack高级配置

    webpack高级配置 1.HTML中img标签的图片资源处理 使用时.只需要在html中正常引用图片即可.webpack就会找到对应的资源进行打包.并修改html中的引用路径 主要是将html中的i ...

  9. python 处理json数据

    python 处理 json数据 以下是登录账号后获取的json数据,headers中注意加入cookie值 需要处理的数据如下: 全部代码如下 #!/usr/bin/env python # -*- ...

  10. HTML 第4章初始CSS3

    什么是CSS? CSS全称为层叠样式表,通常又称为风格样式表. 引用CSS样式: 语法: <h1 styske="color:red;">style属性的应用</ ...