使用@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. wordpress下一篇next_post_link函数的使用方法

    我们在用wordpress开发时经常会用到上一篇下一篇的功能,<?php previous_post_link('%link') ?> <?php next_post_link('% ...

  2. HTTP Status 500 - javax.servlet.ServletException: java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/LoopTag

    我在项目中导入了jar,还是不能使用EL表达式,一运行就出现了下面的额错误: org.apache.jasper.JasperException: javax.servlet.ServletExcep ...

  3. round.606.div2

    A. Happy Birthday, Polycarp! 这个题意我确实没有看懂. 沃日,我懂了,我感觉我似乎都能切掉这题. B. Make Them Odd 这个我也能看懂.

  4. [Python] Python忽略warning警告错误

    Python忽略warning警告错误   1)代码中警告 import warnings warnings.filterwarnings("ignore") 2)忽略命令行下警告 ...

  5. 如何保证最少消费一次redis的list队列数据

    简使用pop,不能保证最少消费一次,比如pop超时可能中途丢失,或者消费者处理过程中异常而未能处理完. 解决此问题有多种方法: 1) 方法一:使用rpoplpush替代pop 这种方法相当于建立了一个 ...

  6. PHP常用的魔术方法及规则

    1. __construct 具有构造函数的类会在每次创建新对象时先调用此方法;初始化工作执行.2. __desstruct 对象的所有引用都被删除或者当对象被显式销毁时执行.3.__call()在对 ...

  7. Java代码题目:计算奖金和完全平方数

    1.计算奖金 题目:企业发放的奖金根据利润提成.利润(I)低于或等于10万元时,奖金可提10%:利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%:2 ...

  8. idea打包web项目

    打包完成的文件在如下路径

  9. Python导入 from lxml import etree 导入不了

    问题在学爬虫,Python 版本是2.7,安装的lxml包是4.3的,在 from lxml import etree 时发现一直报错,网上查询,原来是Python版本和lxml包版本不一致导致的. ...

  10. mestasploit笔记 :MS17-010

    实验环境 操作机 :Kali 2017 操作机IP:172.16.11.2 目标机:Windows 7 目标机IP:172.16.12.2 实验目的 认知Windows远程溢出漏洞的危害 知悉MS17 ...