在后端开发中,有些场景是需要使用定时任务的,例如:定时同步一批数据、定时清理一些数据,在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. string 与 int double 的转化

    #include <iostream> #include <string> #include <sstream> using namespace std; int ...

  2. 【剑指offer】面试题 21. 调整数组顺序使奇数位于偶数前面

    面试题 21. 调整数组顺序使奇数位于偶数前面

  3. python3检测ossfs可用性+钉钉通知

    #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019-12-02 15:16 # @Author : Anthony # @Emai ...

  4. Pair(二进制处理+数位dp)(2019牛客暑期多校训练营(第七场))

    示例: 输入: 33 4 24 5 27 8 5 输出:5 7 31 题意:存在多少对<x,y>满足x&y>C或x^y<C的条件.(0<x<=A,0< ...

  5. 3.03定义常量之enum

    [注:本程序验证是使用vs2013版] #include <stdio.h> #include <stdlib.h> #include <string.h> #pr ...

  6. SSH协议介绍

    SSH概念介绍 SSH是一种网络协议,我们常说的 ssh 一般指其实现,即 OpenSSH,在 shell 中,也就是 ssh 命令. Secure Shell(安全外壳协议,简称SSH)是一种加密的 ...

  7. Java基础系列7——集合系列(1)框架概述

    该系列博文会告诉你如何从入门到进阶,一步步地学习Java基础知识,并上手进行实战,接着了解每个Java知识点背后的实现原理,更完整地了解整个Java技术体系,形成自己的知识框架. 集合框架概述 Jav ...

  8. WebApi接收接收日期格式参数时,日期类型(2019-10-08T16:00:00.000Z)后台接收时间少8小时问题

    前端使用的是elementui的日期控件,将日期格式的数据提交到webapi后台时,接收到的日期格式少了8小时,这个原因是由于时区引起的,应该在WebApiConfig进行配置转成本地时间,解决少8小 ...

  9. sqlite 一些常用的句子

    有关SQLITE最完整的操作语句参考资料,应当是官方网址的http://www.sqlite.org/lang.html这个地方. select max(id)  from table  取最大id ...

  10. semaphore demo 并行 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    import 'dart:async'; import 'package:semaphore/semaphore.dart'; import 'dart:io'; import 'dart:conve ...