springboot通过注解、接口创建定时任务详解

作者:小草莓子桑 时间:2021-06-05 06:00:29 

目录
  • springboot中定时任务的创建

  • springboot通过注解创建定时任务

    • 首先引入pom

    • 直接上代码来一个栗子

    • @Scheduled注解的各个参数

  • springboot通过注接口创建定时任务

    • 实现接口SchedulingConfigurer

    • 主要方法

  • 总结

    项目中经常会用到定时任务,有的人在用quartz,有的人可能自己搭建了一套调度平台,springboot对于定任务的支持,让定时任务的创建变得简单,今天来说说springboot中定时任务的创建。

    springboot中定时任务的创建

    springboot定时任务的创建,这里就主要说两种方式

    • 通过注解创建

    • 通过springboot中提供的接口实现

    springboot通过注解创建定时任务

    首先引入pom

    springboot通过注解、接口创建定时任务详解

    在类上主要用到了@EnableScheduling注解,都在org.springframework:spring-context这个包下

    springboot通过注解、接口创建定时任务详解

    就引入org.springframework:spring-context这个包就可以使用了


    <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${spring.version}</version>
    </dependency>

    直接上代码来一个栗子


    import org.springframework.scheduling.annotation.EnableScheduling;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    /**
    * @createdTime: 2020/4/7 16:00.
    * @version: 1.0 .
    */
    //在类型使用@EnableScheduling来开启定时任务
    @Component
    @EnableScheduling
    public class TestTask {

    private static ThreadLocal<SimpleDateFormat> dateFormat =
               ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    //在方法上使用@Scheduled注解来创建具体的定时任务
       @Scheduled(cron = "0/10 * * * * ?")
       private void task1() {
           System.err.println("执行定时任务了,执行时间为:" + dateFormat.get().format(new Date()));
       }
    }

    看下执行结果:

    springboot通过注解、接口创建定时任务详解

    在类上使用了@EnableScheduling来开启定时任务,使用了@Component是为了注入到spring容器中,这里不用@Component会不会注入我倒没有试过,有试过的小伙伴可以说一下。

    在具体需要定时执行的方法上,使用 @Scheduled注解,这个注解里面的参数有很多种,我这用了cron表达式,这里介绍下这个注解的参数吧

    @Scheduled注解的各个参数

    • cron

    使用方式:@Scheduled(cron = "0/10 * * * * ?")

    源码定义:String cron() default "";

    说明:cron表达式,就是我们日常用的cron,具体的就不贴出来了

    • zone

    使用方式:@Scheduled(zone = "GMT+08:00")

    源码定义:String zone() default "";

    说明:时区,cron表达式会基于这个时区解析,默认为空,会取应用所在服务器的时区,一般不填就可以了,和jdk中TimeZone用的是统一体系,就不具体说了

    • fixedDelay

    使用方式:@Scheduled(fixedDelay = 1)

    源码定义:long fixedDelay() default -1;

    说明:上次执行完了,相隔多长时间以后再执行,单位是毫秒

    • fixedDelayString

    使用方式:

    @Scheduled(fixedDelayString = "1")

    @Scheduled(fixedDelayString = "${配置文件里面的值}")

    源码定义:String fixedDelayString() default "";

    说明:和fixedDelay一样,是string类型的可以填数,单位是毫秒,可以使用配置文件里面的值,使用方法和spring注入配置文件的使用方式一样

    • fixedRate

    使用方式:@Scheduled(fixedRate = 1)

    源码定义:long fixedRate() default -1;

    说明:上次执行开始后,相隔多长时间以后再执行,单位是毫秒

    • fixedRateString

    使用方式:

    @Scheduled(fixedRateString = "1")

    @Scheduled(fixedRateString = "${配置文件里面的值}")

    源码定义:String fixedRateString() default "";

    说明:和fixedRate一样,,是string类型的可以填数,单位是毫秒,可以使用配置文件里面的值,使用方法和spring注入配置文件的使用方式一样

    • initialDelay

    使用方式:@Scheduled(initialDelay = 1)

    源码定义:long initialDelay() default -1;

    说明:上第一次执行后,相隔多长时间以后再执行,单位是毫秒

    • initialDelayString

    使用方式:

    @Scheduled(initialDelayString = "1")

    @Scheduled(initialDelayString = "${配置文件里面的值}")

    源码定义:String initialDelayString() default "";

    说明:和initialDelay一样,,是string类型的可以填数,单位是毫秒,可以使用配置文件里面的值,使用方法和spring注入配置文件的使用方式一样

    springboot通过注接口创建定时任务

    通过接口创建定时,就会比较灵活,定时cron表达式就不用写死在代码的注解上了,可以通过存储到数据库等存储系统中,在接口中来获取这个配置的表达式,这样可以实现一个简易的任务调度平台,通过数据库配置就可以管理定时任务的执行

    实现接口SchedulingConfigurer

    主要用的是这个接口SchedulingConfigurer,他是org.springframework.scheduling.annotation.SchedulingConfigurer这个包路径,其实也是都在org.springframework:spring-context这个包下

    springboot通过注解、接口创建定时任务详解

    就引入org.springframework:spring-context这个包就可以使用了


    <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${spring.version}</version>
    </dependency>

    主要方法

    复写configureTasks方法,这个方法通过ScheduledTaskRegistrar来添加定时任务,大致看方法,入参基本是一个线程对象,后面那个参数和注解里面一样,主要有cron表达式,delay上次执行完了,相隔多长时间以后再执行,initial什么的就不一一赘述了

    springboot通过注解、接口创建定时任务详解

    直接上代码来一个栗子


    import org.springframework.scheduling.TaskScheduler;
    import org.springframework.scheduling.annotation.EnableScheduling;
    import org.springframework.scheduling.annotation.SchedulingConfigurer;
    import org.springframework.scheduling.config.ScheduledTaskRegistrar;
    import org.springframework.scheduling.config.Task;
    import org.springframework.stereotype.Component;

    import java.text.SimpleDateFormat;
    import java.util.Date;

    /**
    * @createdTime: 2020/4/7 18:33.
    * @version: 1.0 .
    */
    @Component
    @EnableScheduling
    public class TestTask2 implements SchedulingConfigurer {

    private static ThreadLocal<SimpleDateFormat> dateFormat =
               ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
       /**
        * Callback allowing a {@link TaskScheduler
        * TaskScheduler} and specific {@link Task Task}
        * instances to be registered against the given the {@link ScheduledTaskRegistrar}.
        *
        * @param taskRegistrar the registrar to be configured.
        */
       @Override
       public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
           System.err.println("假装从数据库中获取到了配置好的定时任务执行计划");
           String cron = "0/10 * * * * ?";
           taskRegistrar.addCronTask(() -> {
               System.err.println("接口定时任务执行定时任务了,执行时间为:" + dateFormat.get().format(new Date()));
           },cron);
       }
    }

    这里通过重写configureTasks方法,使用ScheduledTaskRegistrar对象来创建定时任务,然后表达式可以从数据库等地方读取,演示时候就不写那块代码了,这样可以很简单的实现出来一个简单的任务调度平台
    看下执行结果:

    springboot通过注解、接口创建定时任务详解

    springboot创建定时任务就为大家说到这里,欢迎大家来交流,指出文中一些说错的地方,让我加深认识。

    来源:https://juejin.cn/post/6983315243715788830

    标签:springboot,定时,任务
    0
    投稿

    猜你喜欢

  • Spring Data Jpa的四种查询方式详解

    2021-10-10 10:35:26
  • Spring MVC 简单的hello world的实现

    2023-06-18 02:56:41
  • IDEA插件EasyCode及MyBatis最优配置步骤详解

    2023-11-09 03:19:19
  • java语言基础之标识符和命名规则详解

    2023-04-21 16:50:18
  • Java中数组转List的三种方法与对比分析

    2023-03-27 08:51:03
  • Java动态数组Arraylist存放自定义数据类型方式

    2023-07-25 10:41:30
  • Android WebView无法弹出软键盘的原因及解决办法

    2023-07-07 18:30:00
  • 深入了解Java数据结构和算法之堆

    2022-07-23 19:45:49
  • Java转JSON串的几种方式

    2023-08-24 07:38:47
  • Java反射(Class类,Class对象获取)

    2021-06-27 05:55:24
  • C# 使用SharpZipLib生成压缩包的实例代码

    2021-08-29 20:32:57
  • Spring Cloud集成Nacos Config动态刷新源码剖析

    2022-04-16 11:35:13
  • MAC配置java+jmeter环境变量过程解析

    2021-09-30 00:16:23
  • StringBuilder为什么线程不安全深入讲解

    2023-01-24 01:52:55
  • VisualStudio2019安装C#环境的实现方法

    2021-11-02 18:36:31
  • 优化spring boot应用后6s内启动内存减半

    2021-09-13 02:47:59
  • Android 资源 id详解及的动态获取

    2023-06-25 00:32:21
  • Java下SpringBoot创建定时任务详解

    2023-10-03 01:25:23
  • Android如何在Gradle中更改APK文件名详解

    2021-06-02 12:59:31
  • MyBatis注解CRUD与执行流程深入探究

    2023-07-03 06:19:44
  • asp之家 软件编程 m.aspxhome.com