在后端开发中,有些场景是需要使用定时任务的,例如:定时同步一批数据、定时清理一些数据,在Spring Boot中提供了@Scheduled注解就提供了定时调度的功能,对于简单的、单机的调度方案是足够了的。这篇文章准备用实际案例看下@Scheduled的用法。

开发实战

  1. 新建Spring Boot工程,主pom文件内容如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>online.javaadu.schedule</groupId>
    <artifactId>scheduledemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>scheduledemo</name>
    <description>Demo project for Spring Boot</description> <properties>
    <java.version>1.8</java.version>
    </properties> <dependencies>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    </dependency> <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
    <exclusion>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    </exclusion>
    </exclusions>
    </dependency>
    </dependencies> <build>
    <plugins>
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
    </plugins>
    </build> </project>
  2. 新建定时任务组件,使用@Scheduled注解修饰要调度的方法,在该方法中会打印当前的时间。

    package online.javaadu.schedule.scheduledemo;
    
    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 ScheduledTasks { private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class); private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); //第一次执行之前延后10秒钟;后续每隔5秒执行1次
    @Scheduled(fixedRate = 5000, initialDelay = 10000)
    public void reportCurrentTime() {
    log.info("The time is now {}", dateFormat.format(new Date()));
    }
    }
  3. 在ScheduledemoApplication中开启定时调度能力——即开启@Scheduled注解的定时调度功能,并在系统刚起来的时候打印一行日志,用来体现上一步中的initialDelay的作用。

    package online.javaadu.schedule.scheduledemo;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.scheduling.annotation.EnableScheduling; import java.text.SimpleDateFormat;
    import java.util.Date; @SpringBootApplication
    @EnableScheduling
    public class ScheduledemoApplication { private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); public static void main(String[] args) {
    SpringApplication.run(ScheduledemoApplication.class, args);
    log.info("---The time is now {}", dateFormat.format(new Date()));
    } }
  4. 点击运行后,该demo的运行结果如下,可以看出,23:15:35应用启动,过了10秒钟定时调度任务才开始执行,然后是每隔5秒钟打印一次时间。

分析解释

我们一起来看下@Scheduled注解的源码,看看除了上面的例子里提供的案例,该注解还有哪些功能呢?

  • cron,可以支持更复杂的时间复杂度
  • zone,解析cron表达式的时候解析时区
  • fixedDelay(和fixedDelayString),两次调度之间需要加一个固定的延迟
  • fixedRate(和fixedRateString),没隔多久需要调度一次
  • initialDelay(和initialDelayString),第一次调度之前需要延迟多久
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled { /**
* 特殊的cron表达式,如果设置成这个值,则表示将定时调度器关闭,不再调度。
*/
String CRON_DISABLED = ScheduledTaskRegistrar.CRON_DISABLED; /**
* cron表达式,可以支持复杂的定时调度需求
*/
String cron() default ""; /**
* cron表达式解析的时候,解析依赖的时区
*/
String zone() default ""; /**
* 两次调度触发之间暂停的毫秒数,Long类型
*/
long fixedDelay() default -1; /**
* 两次调度触发之间暂停的毫秒数,String类型
*/
String fixedDelayString() default ""; /**
* 每隔几毫秒调度一次
*/
long fixedRate() default -1; /**
* 每隔几毫秒调度一次,String类型
*/
String fixedRateString() default ""; /**
* 第一次执行之前,延迟多少毫秒
*/
long initialDelay() default -1; /**
* 第一次执行之前,延迟多少毫秒,String类型
*/
String initialDelayString() default ""; }
来源:吉林网站优化

Spring Boot 2.x实战之定时任务调度的更多相关文章

  1. Spring Boot 揭秘与实战 附录 - Spring Boot 公共配置

    Spring Boot 公共配置,配置 application.properties/application.yml 文件中. 摘自:http://docs.spring.io/spring-boot ...

  2. Spring Boot 揭秘与实战 自己实现一个简单的自动配置模块

    文章目录 1. 实战的开端 – Maven搭建 2. 参数的配置 - 属性参数类 3. 真的很简单 - 简单的服务类 4. 自动配置的核心 - 自动配置类 5. spring.factories 不要 ...

  3. Spring Boot 揭秘与实战 源码分析 - 工作原理剖析

    文章目录 1. EnableAutoConfiguration 帮助我们做了什么 2. 配置参数类 – FreeMarkerProperties 3. 自动配置类 – FreeMarkerAutoCo ...

  4. Spring Boot 揭秘与实战 源码分析 - 开箱即用,内藏玄机

    文章目录 1. 开箱即用,内藏玄机 2. 总结 3. 源代码 Spring Boot提供了很多”开箱即用“的依赖模块,那么,Spring Boot 如何巧妙的做到开箱即用,自动配置的呢? 开箱即用,内 ...

  5. Spring Boot 揭秘与实战(九) 应用监控篇 - 自定义监控端点

    文章目录 1. 继承 AbstractEndpoint 抽象类 2. 创建端点配置类 3. 运行 4. 源代码 Spring Boot 提供的端点不能满足我们的业务需求时,我们可以自定义一个端点. 本 ...

  6. Spring Boot 揭秘与实战(九) 应用监控篇 - HTTP 健康监控

    文章目录 1. 内置 HealthIndicator 监控检测 2. 自定义 HealthIndicator 监控检测 3. 源代码 Health 信息是从 ApplicationContext 中所 ...

  7. Spring Boot 揭秘与实战(九) 应用监控篇 - HTTP 应用监控

    文章目录 1. 快速开始 2. 监控和管理端点3. 定制端点 2.1. health 应用健康指标 2.2. info 查看应用信息 2.3. metrics 应用基本指标 2.4. trace 基本 ...

  8. Spring Boot 揭秘与实战(八) 发布与部署 - 远程调试

    文章目录 1. 依赖 2. 部署 3. 调试 4. 源代码 设置远程调试,可以在正式环境上随时跟踪与调试生产故障. 依赖 在 pom.xml 中增加远程调试依赖. <plugins> &l ...

  9. Spring Boot 揭秘与实战(八) 发布与部署 - 开发热部署

    文章目录 1. spring-boot-devtools 实现热部署 2. Spring Loaded 实现热部署 3. 模板文件热部署 4. 源代码 Spring Boot 支持页面与类文件的热部署 ...

随机推荐

  1. mycat实现读写分离

    1 mysql已经配置好了主从 2 linux 安装java环境 3 linux 安装mycat cd /usr/local # 下载mycat wget http://dl.mycat.io/1.6 ...

  2. react-native-typescript-项目环境搭建

    1.yarn global add create-react-native-app //全局安装 2.create-react-native-app 项目名称 3.yarn add typescrip ...

  3. [转帖]在 k8s 中通过 Ingress 配置域名访问

    在 k8s 中通过 Ingress 配置域名访问 https://juejin.im/post/5db8da4b6fb9a0204520b310 在上篇文章中我们已经使用 k8s 部署了第一个应用,此 ...

  4. 如何在运行时更改JMeter的负载

    在某些情况下,能够在不停止测试的情况下更改性能测试产生的负载是有用的或必要的.这可以通过使用Apache JMeter™的恒定吞吐量计时器和Beanshell服务器来完成.在这篇文章中,我们将介绍如何 ...

  5. 《Mysql - 自增主键为何不是连续的?》

    一:自增主键是连续的么? - 自增主键不能保证连续递增. 二:自增值保存在哪里? - 当使用 show create table `table_name`:时,会看到 自增值,也就是 AUTO_INC ...

  6. java笔记3

    面向对象的特点:   1.封装:   2.继承   3.多态 好处:   是一种符合人们思考习惯的思想  可以将复杂的事情简单化  将程序员从执行者变为指挥者 二 类与对象 成员变量与局部变量的区别: ...

  7. linux系统状态脚本

    #!/bin/bashprintf "%10s\n" "##主机名##"printf "%-10s\n" "$(hostname) ...

  8. Docker简易安装及命令实例

    docker ~ ~ ~ Docker 是一个开源的应用容器引擎,基于 Go 语言 并遵从Apache2.0协议开源. Docker 可以让开发者打包他们的应用以及依赖包到一个轻量级.可移植的容器中, ...

  9. 不一样的go语言-athens源码概览

    前言   上一篇文章介绍了athens私服的安装以及vgo download protocol的简要介绍.本文着重介绍go proxy sever的实现原理以及athens是如何实现的. go get ...

  10. 「CTS2019」珍珠

    「CTS2019」珍珠 解题思路 看了好多博客才会,问题即要求有多少种方案满足数量为奇数的变量数 \(\leq n-2m\).考虑容斥,令 \(F(k)\) 为恰好有 \(n\) 个变量数量为奇数的方 ...