使用@Scheduled 可以很容易实现定时任务

spring boot的版本 2.1.6.RELEASE

package com.abc.demo.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit; @EnableScheduling
@Component
public class ScheduleSetting { private final Logger logger = LoggerFactory.getLogger(Tasks.class); @Scheduled(fixedRate = 10000, initialDelay = 2000)
public void scheduleRead() {
try {
long timeStamp = System.currentTimeMillis();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Thread thread = Thread.currentThread();
System.out.println("cron1任务开始,start=" + simpleDateFormat.format(timeStamp) + ", threadId=" + thread.getId() + ", threadName=" + thread.getName());
long endStamp = System.currentTimeMillis();
try {
TimeUnit.SECONDS.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("cron1任务正在运行的线程名称:" + thread.getName() + " 结束,start=" + simpleDateFormat.format(timeStamp) + ",end=" + simpleDateFormat.format(endStamp));
System.out.println("++++++++++++++++++++++++");
} catch (Exception e) {
logger.error(e.getMessage());
}
} @Scheduled(fixedRate = 5000, initialDelay = 1000)
public void scheduleConvert() {
try { long timeStamp = System.currentTimeMillis();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Thread thread = Thread.currentThread();
System.out.println("cron2任务开始,start=" + simpleDateFormat.format(timeStamp) + ", threadId=" + thread.getId() + ", threadName=" + thread.getName());
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
long endStamp = System.currentTimeMillis();
System.out.println("cron2任务正在运行的线程名称:" + thread.getName() + " 结束,start=" + simpleDateFormat.format(timeStamp) + ",end=" + simpleDateFormat.format(endStamp));
System.out.println("====================");
} catch (Exception e) {
logger.error(e.getMessage());
}
} }

运行输出内容为

cron2任务开始,start=2019-10-11 17:31:52, threadId=34, threadName=scheduling-1
cron2任务正在运行的线程名称:scheduling-1 结束,start=2019-10-11 17:31:52,end=2019-10-11 17:32:02
====================
cron1任务开始,start=2019-10-11 17:32:02, threadId=34, threadName=scheduling-1
cron1任务正在运行的线程名称:scheduling-1 结束,start=2019-10-11 17:32:02,end=2019-10-11 17:32:02
++++++++++++++++++++++++
cron2任务开始,start=2019-10-11 17:32:22, threadId=34, threadName=scheduling-1
cron2任务正在运行的线程名称:scheduling-1 结束,start=2019-10-11 17:32:22,end=2019-10-11 17:32:32

……

注:

  cron2执行完后才会执行cron1

原因:

  spring默认是以单线程执行任务调度

  spring的定时任务默认最大运行线程数为1,多个任务执行起来时间会有问题

1.配置线程池

在配置文件application.properties中添加

# 线程池大小
spring.task.scheduling.pool.size=5
# 线程名前缀
spring.task.scheduling.thread-name-prefix=myScheduling-

输出内容变为

cron2任务开始,start=2019-10-11 17:34:48, threadId=34, threadName=myScheduling-1
cron1任务开始,start=2019-10-11 17:34:49, threadId=35, threadName=myScheduling-2
cron2任务正在运行的线程名称:myScheduling-1 结束,start=2019-10-11 17:34:48,end=2019-10-11 17:34:58
====================
cron2任务开始,start=2019-10-11 17:34:58, threadId=34, threadName=myScheduling-1
cron2任务正在运行的线程名称:myScheduling-1 结束,start=2019-10-11 17:34:58,end=2019-10-11 17:35:08
====================
cron2任务开始,start=2019-10-11 17:35:08, threadId=57, threadName=myScheduling-3
cron1任务正在运行的线程名称:myScheduling-2 结束,start=2019-10-11 17:34:49,end=2019-10-11 17:34:49

……

注:

  多线程下,cron1和cron2不用互相等待了,但是同一个任务还是需要等待的

2.并发

修改代码

package com.abc.demo.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit; @EnableScheduling
@Component
@EnableAsync
public class ScheduleSetting { private final Logger logger = LoggerFactory.getLogger(Tasks.class); @Async
@Scheduled(fixedRate = 10000, initialDelay = 2000)
public void scheduleRead() {
try {
long timeStamp = System.currentTimeMillis();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Thread thread = Thread.currentThread();
System.out.println("cron1任务开始,start=" + simpleDateFormat.format(timeStamp) + ", threadId=" + thread.getId() + ", threadName=" + thread.getName());
long endStamp = System.currentTimeMillis();
try {
TimeUnit.SECONDS.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("cron1任务正在运行的线程名称:" + thread.getName() + " 结束,start=" + simpleDateFormat.format(timeStamp) + ",end=" + simpleDateFormat.format(endStamp));
System.out.println("++++++++++++++++++++++++");
} catch (Exception e) {
logger.error(e.getMessage());
}
} @Async
@Scheduled(fixedRate = 5000, initialDelay = 1000)
public void scheduleConvert() {
try { long timeStamp = System.currentTimeMillis();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Thread thread = Thread.currentThread();
System.out.println("cron2任务开始,start=" + simpleDateFormat.format(timeStamp) + ", threadId=" + thread.getId() + ", threadName=" + thread.getName());
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
long endStamp = System.currentTimeMillis();
System.out.println("cron2任务正在运行的线程名称:" + thread.getName() + " 结束,start=" + simpleDateFormat.format(timeStamp) + ",end=" + simpleDateFormat.format(endStamp));
System.out.println("====================");
} catch (Exception e) {
logger.error(e.getMessage());
}
} }

输出的内容

cron2任务开始,start=2019-10-11 17:39:53, threadId=57, threadName=task-1
cron1任务开始,start=2019-10-11 17:39:54, threadId=59, threadName=task-2
cron2任务开始,start=2019-10-11 17:39:58, threadId=61, threadName=task-3
cron2任务开始,start=2019-10-11 17:40:03, threadId=63, threadName=task-4
cron2任务正在运行的线程名称:task-1 结束,start=2019-10-11 17:39:53,end=2019-10-11 17:40:03
====================
cron1任务开始,start=2019-10-11 17:40:04, threadId=64, threadName=task-5
cron2任务开始,start=2019-10-11 17:40:08, threadId=65, threadName=task-6
cron2任务正在运行的线程名称:task-3 结束,start=2019-10-11 17:39:58,end=2019-10-11 17:40:08
====================
cron2任务开始,start=2019-10-11 17:40:13, threadId=66, threadName=task-7
cron2任务正在运行的线程名称:task-4 结束,start=2019-10-11 17:40:03,end=2019-10-11 17:40:13
====================
cron1任务正在运行的线程名称:task-2 结束,start=2019-10-11 17:39:54,end=2019-10-11 17:39:54

说明: 

  @EnableAsync开启多线程

  @Async标记其为一个异步任务

  每个定时任务都是在通过不同的线程来处理,线程名的前缀成了task-

  线程默认为10个

修改配置

spring.task.execution.thread-name-prefix=mytask-
spring.task.execution.pool.core-size=5

重新运行的输出

cron2任务开始,start=2019-10-11 17:44:00, threadId=56, threadName=mytask-1
cron1任务开始,start=2019-10-11 17:44:01, threadId=57, threadName=mytask-2
cron2任务开始,start=2019-10-11 17:44:05, threadId=58, threadName=mytask-3
cron2任务开始,start=2019-10-11 17:44:10, threadId=59, threadName=mytask-4
cron2任务正在运行的线程名称:mytask-1 结束,start=2019-10-11 17:44:00,end=2019-10-11 17:44:10
====================
cron1任务开始,start=2019-10-11 17:44:11, threadId=60, threadName=mytask-5
cron2任务正在运行的线程名称:mytask-3 结束,start=2019-10-11 17:44:05,end=2019-10-11 17:44:15
====================
cron2任务开始,start=2019-10-11 17:44:15, threadId=58, threadName=mytask-3
cron2任务开始,start=2019-10-11 17:44:20, threadId=56, threadName=mytask-1
cron2任务正在运行的线程名称:mytask-4 结束,start=2019-10-11 17:44:10,end=2019-10-11 17:44:20
====================
cron1任务正在运行的线程名称:mytask-2 结束,start=2019-10-11 17:44:01,end=2019-10-11 17:44:01

曾经在幽幽暗暗,反反覆覆中追问,才知道平平淡淡从从容容才是真

再回首恍然如梦,再回首我心依旧,只有那无尽的长路陪伴我

spring boot 2X中@Scheduled实现定时任务及多线程配置的更多相关文章

  1. spring boot项目中处理Schedule定时任务

    项目中,因为使用了第三方支付(支付宝和微信支付),支付完毕后,第三方支付平台一般会采用异步回调通知的方式,通知商户支付结果,然后商户根据通知内容,变更商户项目支付订单的状态.一般来说,为了防止商户项目 ...

  2. 【tmos】spring boot项目中处理Schedule定时任务

    我的代码 /** * Author:Mr.X * Date:2017/10/30 14:54 * Description: */ @Component @Configurable @EnableSch ...

  3. 在spring boot环境中使用fastjson + redis的高速缓存技术

    因为项目需求,需要在spring boot环境中使用redis作数据缓存.之前的解决方案是参考的http://wiselyman.iteye.com/blog/2184884,具体使用的是Jackso ...

  4. 你真的理解 Spring Boot 项目中的 parent 吗?

    前面和大伙聊了 Spring Boot 项目的三种创建方式,这三种创建方式,无论是哪一种,创建成功后,pom.xml 坐标文件中都有如下一段引用: <parent> <groupId ...

  5. Spring Boot项目中使用Swagger2

    Swagger2是一款restful接口文档在线生成和在线接口调试工具,Swagger2在Swagger1.x版本的基础上做了些改进,下面是在一个Spring Boot项目中引入Swagger2的简要 ...

  6. spring boot JPA中实体类常用注解

    spring boot jpa中的注解很多,参数也比较多.没必要全部记住,但是经常查看官方文档也比较麻烦,记录一下一些常用的注解.通过一些具体的例子来帮助记忆. @Entity @Table(name ...

  7. Spring Boot 2中对于CORS跨域访问的快速支持

    原文:https://www.jianshu.com/p/840b4f83c3b5 目前的程序开发,大部分都采用前后台分离.这样一来,就都会碰到跨域资源共享CORS的问题.Spring Boot 2 ...

  8. spring boot配置文件中 spring.mvc.static-path-pattern 配置项

    spring boot项目中的静态资源文件存放在static文件下面,当通过浏览器访问这些静态文件时,发现必须要添加static作为前缀才能访问,折腾了一番后发现,这个前缀跟 spring.mvc.s ...

  9. RabbitMQ入门:在Spring Boot 应用中整合RabbitMQ

    在上一篇随笔中我们认识并安装了RabbitMQ,接下来我们来看下怎么在Spring Boot 应用中整合RabbitMQ. 先给出最终目录结构: 搭建步骤如下: 新建maven工程amqp 修改pom ...

随机推荐

  1. 使用NSProxy和NSObject设计代理类的差异

    经常发现在一些需要使用消息转发而创建代理类时, 不同的程序员都有着不同的使用方法, 有些采用继承于NSObject, 而有一些采用继承自NSProxy. 二者都是Foundation框架中的基类, 并 ...

  2. 牛客OI周赛10-普及组-A眼花缭乱的街市-(加速+二分)

    https://ac.nowcoder.com/acm/contest/901/A 很简单的一道题,全场只有20+AC,卡时间.新学了cin加速语法和数组二分查找的函数调用. 知道有个读写挂,可以加速 ...

  3. PostgreSQL 执行计划

    简介 PostgreSQL是“世界上最先进的开源关系型数据库”.因为出现较晚,所以客户人群基数较MySQL少,但是发展势头很猛,最大优势是完全开源. MySQL是“世界上最流行的开源关系型数据库”.当 ...

  4. 通过日志解决问题的一个小例子-http换端口

    这个例子是将http服务的监听端口改为8999后重启服务报错: 此时查看日志/var/log/message,显示如下: 如红笔所示轨迹得到设置端口类型的命令:semanage port -a -t ...

  5. Xamarin.Forms快速入门-深入探讨

    官网链接 项目介绍 以Notes项目为例,The Notes application consists of one solution containing four projects, as sho ...

  6. 新blog

    www.nancheng58.xyz 欢迎来访 骗访客量 我之前的blog是在csdn上的 https://blog.csdn.net/sinat_34550050 这里算是个在csdn的镜像吧 不过 ...

  7. TCP/IP协议族基本知识

    常见的网络拓扑 两台主机通信的过程:应用进程产生消息,经由主机的 TCP/IP 协议栈发送到局域网(LAN),最后经过广域网(目前最大的广域网的因特网)中的网络设备(路由器)传给目的主机所在的局域网( ...

  8. gitlab 上传代码

    #生成公钥ssh-keygen -t ed25519 -C "xxx@tianwang.com"#拷贝公钥pbcopy < ~/.ssh/id_ed25519.pub 在网页 ...

  9. Fix multiple GPUs fails in training Mask_RCNN

    Test with: Keras: 2.2.4Python: 3.6.9Tensorflow: 1.12.0 ================== Problem: Using code from h ...

  10. Rose与PowerDesigner:两款UML建模工具的对比

    声明 本文转载自:Rose与PowerDesigner:两款UML建模工具的对比 正文 本文和大家重点讨论一下Rose与PowerDesigner:两款UML建模工具的对比,Rose和PowerDes ...