springboot扫描组件_Spring Boot入门系列(八)整合定时任务Task,一秒搞定定时任务...

4ea9136d8db46666df6523348d98f56b.gif

前面介绍了Spring Boot 中的整合Redis缓存已经如何实现数据缓存功能。不清楚的朋友可以看看之前的文章。

今天主要讲解Springboot整合定时任务。在SpringMvc中也会用到很多的定时任务,主要是通过Quartz实现。但是在Spring MVC中使用这些插件相对还是比较麻烦的:要增加一些依赖包,然后加入各种配置等等。Spring Boot相对就简单很多了,现在就来说说Spring Boot 是怎么实现定时任务的。

一、使用注解@EnableScheduling

在application启动类中,加上@EnableScheduling 注解,Spring Boot 会自动扫描任务类,开启定时任务。

package com.weiz;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.ComponentScan;import org.springframework.scheduling.annotation.EnableAsync;import org.springframework.scheduling.annotation.EnableScheduling;import tk.mybatis.spring.annotation.MapperScan;@SpringBootApplication//扫描 mybatis mapper 包路径@MapperScan(basePackages = "com.weiz.mapper")//扫描 所有需要的包, 包含一些自用的工具类包 所在的路径@ComponentScan(basePackages = {"com.weiz","org.n3r.idworker"})//开启定时任务@EnableScheduling//开启异步调用方法@EnableAsyncpublic class SpringBootStarterApplication {    public static void main(String[] args) {        SpringApplication.run(SpringBootStarterApplication.class, args);    }}

说明:

1、@EnableScheduling 为开启定时任务。

2、@ComponentScan 定义扫描包的路径。

二、创建任务类,定义@Component 组件

创建com.weiz.tasks包,在tasks包里增加TestTask任务类,加上@Component 注解,那么TestTask就会作为组件被容器扫描到。扫描到之后Spring Boot容器就会根据任务类里面定义的时间,定时执行了。

package com.weiz.tasks;import java.text.SimpleDateFormat;import java.util.Date;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Componentpublic class TestTask {    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");    // 定义每过3秒执行任务    @Scheduled(fixedRate = 3000)    // @Scheduled(cron = "4-40 * * * * ?")    public void reportCurrentTime() {        System.out.println("现在时间:" + dateFormat.format(new Date()));    }}

说明:@Scheduled 是定时任务执行的时间,可以每个一段时间执行,也可以使用cron 表达式定义执行时间。

三、Cron表达式

Spring Boot 定时任务支持每个一段时间执行或是使用cron 表达式定义执行时间。关于cron表达式,我之前的文章介绍过,大家可以看我以前的文章:《Quartz.NET总结(二)CronTrigger和Cron表达式》

四、测试

启动程序之后,就可以看到系统每隔3s,会打印系统时间。

4c7fb05e5d5accdc96a8aed97242dbcb.png

最后

以上,就把Spring Boot整合定时任务简单介绍完了,是不是特别简单,下一篇我会介绍Spring boot 的异步任务。

推荐阅读:

  • Spring Boot整合Redis代码详解,四步搞定!

  • Spring Boot入门系列(六)Spring Boot整合Mybatis「附详细步骤

  • SpringBoot入门系列(五)Thymeleaf的常用标签和用

  • SpringBoot入门系列(四)整合Thymeleaf模板引擎

  • SpringBoot入门系列(三)SpringBoot资源文件属性配置

  • SpringBoot入门系列(二)Controller介绍及如何统一返回json数据

  • SpringBoot入门系列(一)如何快速创建SpringBoot项

    9169b7dae88990db2a052b50f49a5ba6.png

157634300df29536be0db664cd21a24a.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值