本文源码:GitHub·点这里 || GitEE·点这里

一、定时任务

1、基本概念

按照指定时间执行的程序。

2、使用场景

数据分析
数据清理
系统服务监控

二、同步和异步

1、基本概念

同步调用

程序按照代码顺序依次执行,每一行程序都必须等待上一行程序执行完成之后才能执行;

异步调用

顺序执行时,不等待异步调用的代码块返回结果就执行后面的程序。

2、使用场景

短信通知
邮件发送
批量数据入缓存

三、SpringBoot2.0使用定时器

1、定时器执行规则注解

@Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
@Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
@Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
@Scheduled(cron="/5") :通过cron表达式定义规则

2、定义时间打印定时器

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 时间定时任务
*/
@Component
public class TimeTask {
Logger LOG = LoggerFactory.getLogger(TimeTask.class.getName()) ;
private static final SimpleDateFormat format =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
/**
* 每3秒打印一次系统时间
*/
@Scheduled(fixedDelay = 3000)
public void systemDate (){
LOG.info("当前时间::::"+format.format(new Date()));
}
}

3、启动类开启定时器注解

@EnableScheduling   // 启用定时任务
@SpringBootApplication
public class TaskApplication {
public static void main(String[] args) {
SpringApplication.run(TaskApplication.class,args) ;
}
}

四、SpringBoot2.0使用异步任务

1、编写异步任务类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class AsyncTask {
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncTask.class) ;
/*
* [ asyncTask1-2] com.boot.task.config.AsyncTask : ======异步任务结束1======
* [ asyncTask1-1] com.boot.task.config.AsyncTask : ======异步任务结束0======
*/
// 只配置了一个 asyncExecutor1 不指定也会默认使用
@Async
public void asyncTask0 () {
try{
Thread.sleep(5000);
}catch (Exception e){
e.printStackTrace();
}
LOGGER.info("======异步任务结束0======");
}
@Async("asyncExecutor1")
public void asyncTask1 () {
try{
Thread.sleep(5000);
}catch (Exception e){
e.printStackTrace();
}
LOGGER.info("======异步任务结束1======");
}
}

2、指定异步任务执行的线程池

这里可以不指定,指定执行的线城池,可以更加方便的监控和管理异步任务的执行。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 定义异步任务执行的线程池
*/
@Configuration
public class TaskPoolConfig {
@Bean("asyncExecutor1")
public Executor taskExecutor1 () {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数10:线程池创建时候初始化的线程数
executor.setCorePoolSize(10);
// 最大线程数20:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
executor.setMaxPoolSize(20);
// 缓冲队列200:用来缓冲执行任务的队列
executor.setQueueCapacity(200);
// 允许线程的空闲时间60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
executor.setKeepAliveSeconds(60);
// 线程池名的前缀:设置好了之后可以方便定位处理任务所在的线程池
executor.setThreadNamePrefix("asyncTask1-");
/*
线程池对拒绝任务的处理策略:这里采用了CallerRunsPolicy策略,
当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;
如果执行程序已关闭,则会丢弃该任务
*/
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
executor.setWaitForTasksToCompleteOnShutdown(true);
// 设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住。
executor.setAwaitTerminationSeconds(600);
return executor;
}
}

3、启动类添加异步注解

@EnableAsync        // 启用异步任务
@SpringBootApplication
public class TaskApplication {
public static void main(String[] args) {
SpringApplication.run(TaskApplication.class,args) ;
}
}

4、异步调用的测试接口

@RestController
public class TaskController {
@Resource
private AsyncTask asyncTask ;
@RequestMapping("/asyncTask")
public String asyncTask (){
asyncTask.asyncTask0();
asyncTask.asyncTask1();
return "success" ;
}
}

五、源代码地址

GitHub·地址
https://github.com/cicadasmile/spring-boot-base
GitEE·地址
https://gitee.com/cicadasmile/spring-boot-base

SpringBoot2.0 基础案例(04):定时任务和异步任务的使用方式的更多相关文章

  1. SpringBoot2.0 基础案例(12):基于转账案例,演示事务管理操作

    本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.事务管理简介 1.事务基本概念 一组业务操作ABCD,要么全部 ...

  2. SpringBoot2.0 基础案例(14):基于Yml配置方式,实现文件上传逻辑

    本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.文件上传 文件上传是项目开发中一个很常用的功能,常见的如头像上 ...

  3. SpringBoot2.0 基础案例(13):基于Cache注解模式,管理Redis缓存

    本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.Cache缓存简介 从Spring3开始定义Cache和Cac ...

  4. SpringBoot2.0基础案例(01):环境搭建和RestFul风格接口

    一.SpringBoot 框架的特点 1.SpringBoot2.0 特点 1)SpringBoot继承了Spring优秀的基因,上手难度小 2)简化配置,提供各种默认配置来简化项目配置 3)内嵌式容 ...

  5. SpringBoot2.0 基础案例(10):整合Mybatis框架,集成分页助手插件

    一.Mybatis框架 1.mybatis简介 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获 ...

  6. SpringBoot2.0 基础案例(09):集成JPA持久层框架,简化数据库操作

    一.JAP框架简介 JPA(Java Persistence API)意即Java持久化API,是Sun官方在JDK5.0后提出的Java持久化规范.主要是为了简化持久层开发以及整合ORM技术,结束H ...

  7. SpringBoot2.0 基础案例(07):集成Druid连接池,配置监控界面

    一.Druid连接池 1.druid简介 Druid连接池是阿里巴巴开源的数据库连接池项目.Druid连接池为监控而生,内置强大的监控功能,监控特性不影响性能.功能强大,能防SQL注入,内置Login ...

  8. SpringBoot2.0 基础案例(03):配置系统全局异常映射处理

    一.异常分类 这里的异常分类从系统处理异常的角度看,主要分类两类:业务异常和系统异常. 1.业务异常 业务异常主要是一些可预见性异常,处理业务异常,用来提示用户的操作,提高系统的可操作性. 常见的业务 ...

  9. SpringBoot2.0 基础案例(16):配置Actuator组件,实现系统监控

    本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.Actuator简介 1.监控组件作用 在生产环境中,需要实时 ...

随机推荐

  1. codeforces 631C C. Report

    C. Report time limit per test 2 seconds memory limit per test 256 megabytes input standard input out ...

  2. Agc011_F Train Service Planning

    先放题面,再放LHX巨佬题解 接着就是%%%.$orz.Oro.Or2.Otz.OTL.sto.rzo.Jto$.On_.○| ̄|_啊 模拟赛里直接把这道题刚掉了 一题升天·爆踩全场 这题思维跨越度已 ...

  3. findBug 错误修改指南

      1. EC_UNRELATED_TYPESBug: Call to equals() comparing different types Pattern id: EC_UNRELATED_TYPE ...

  4. HDOJ1242(延时迷宫BFS+优先队列)

    Rescue Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Subm ...

  5. requests 的使用

    1.1.实例引入 # 引入Requests库 import requests   # 发起GET请求 response = requests.get('https://www.baidu.com/') ...

  6. shell入门-cut命令

    命令:cut 选项:-d:-f  指定第几段由“:(分割符)”分割的段 -c    指定第几个字符 说明:选取命令,选取一段数据中我们想要的,一般是针对每行来分析选取的 [root@wangshaoj ...

  7. HTTP之首部

    http报文包括起始行.首部和主体.     HTTP请求/响应起始行 请求组成: 方法 + 请求URL + HTTP版本 响应组成: HTTP版本 + 数字状态码 + 描述状态的原因短语    HT ...

  8. C++之Stack模板类

    假设有这样一种情况:某人将一车文件交给小王.倘若小王的抽屉是空的,那么小王从车上取出最上面的文件将其放入抽屉:倘若抽屉是满的,小王从抽屉中取出最上面的文件,放入垃圾篓:倘若抽屉即不空也未满,那么小王抛 ...

  9. 【总结整理】JQuery基础学习---样式篇

    进入官方网站获取最新的版本 http://jquery.com/download/    中文 https://www.jquery123.com/ <!--JQuery:轻量级的JavaScr ...

  10. Freemarker01

    1 如何使用freemarker 1.1 导包 freemarker-2.3.19.jar 1.2 创建一个ftl文件作为模板 1.3 创建一个方法来将ftl模板和数据组合起来 2 利用maven实现 ...