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

目录springboot中定时任务的创建springboot通过注解创建定时任务首先引入pom直接上代码来一个栗子@Scheduled注解的各个参数springboot通过注接口创建定时任务实现接口SchedulingConfigurer主要方法总结

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

springboot中定时任务的创建

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

通过注解创建 通过springboot中提供的接口实现

springboot通过注解创建定时任务

首先引入pom

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

就引入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@EnableSchedulingpublic 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()));    }}

看下执行结果:

在类上使用了@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这个包下

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

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

主要方法

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

直接上代码来一个栗子

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@EnableSchedulingpublic 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通过注解、接口创建定时任务的文章就介绍到这了,更多相关springboot创建定时任务内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

一个背包,几本书,所有喜欢的歌,

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

相关文章:

你感兴趣的文章:

标签云: