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

发布时间:2022-04-02 16:21:10 作者:iii
来源:亿速云 阅读:178

本篇内容介绍了“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注解的各个参数

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

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

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

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

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

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

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

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

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

使用方式:

@Scheduled(fixedDelayString = "1")

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

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

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

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

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

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

使用方式:

@Scheduled(fixedRateString = "1")

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

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

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

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

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

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

使用方式:

@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怎么通过注解、接口创建定时任务”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. SpringBoot注解
  2. 创建springboot定时任务的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot

上一篇:SpringBoot怎么统一后端返回格式

下一篇:基于SpringBoot加载Mybatis的TypeAlias问题怎么解决

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》