在后端开发中,有些场景是需要使用定时任务的,例如:定时同步一批数据、定时清理一些数据,在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. web应用中实现同一个账号,后面登录的会把前面登录的挤下线

    在web应用中假如没有做会话控制,会出现这样的情况,A登录了账号,B也登录了账号,都是同样的账号,A修改了信息,B会看到修改的信息,这样的用户体验不好,B会觉得我没有修改啊,为什么信息会改变.而做会话 ...

  2. Apache Kafka + Spark Streaming Integration

    1.目标 为了构建实时应用程序,Apache Kafka  - Spark Streaming Integration是最佳组合.因此,在本文中,我们将详细了解Kafka中Spark Streamin ...

  3. learning、trying、teaching

    在工作中学习和提升,学以致用,学习的效果是最好的:工作后学习不需要大段时间,而是要挤出时间,利用时间碎片来学习. 1,Learning 这是第一阶段,看书.google.看视频.看别人的博客,但要是“ ...

  4. git使用代理加快下载

    git -c http.proxy=socks5://127.0.0.1:1086 clone https://github.com/.../...

  5. RequestBody只能读取一次的问题

    一.为什么只能读一次 原因很简单:因为是流.想想看,java中的流也是只能读一次,因为读完之后,position就到末尾了. 二.解决办法 思路:第一次读的时候,把流数据暂存起来.后面需要的时候,直接 ...

  6. C#只读属性

    using System; using System.Collections.Generic; using System.Text; namespace 面向对象 { class Person { / ...

  7. node作为前台的项目如何打包静态js和css并生成版本号,loader插件的使用

    一.使用场景: 1.node创建的前台项目需要输入地址展示页面 2.有设置缓存或者cdn的需要在静态文件更改时能使用新的而不是缓存的,需要版本号这里 3.可能需要压缩静态文件的 二.一些参考地址,需要 ...

  8. 移动Web深度剖析

    随着前端技术的急速发展,随着互联网行业的日益发展,HTML5作为一种比较新型的开发技术早已经被很多大的企业所应用,通过HTML5语言可以开发适用于任何设备上的酷炫网站页面,所以HTML5的发展趋势可想 ...

  9. Jmeter学习笔记(十五)——常用的4种参数化方式

    一.Jmeter参数化概念 当使用JMeter进行测试时,测试数据的准备是一项重要的工作.若要求每次迭代的数据不一样时,则需进行参数化,然后从参数化的文件中来读取测试数据. 参数化是自动化测试脚本的一 ...

  10. JSP中Get提交方式的中文乱码解决

    最近对JSP&Servlert的原理很感兴趣,所以今天花时间看了一下:无奈在一个编码问题上困扰很久 这是我的解决思路: (1)检查网页(html/jsp)页面的编码: (2)检查服务器端的处理 ...