- 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
- // 开启异步调用方法
- @EnableAsync
- public 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;
- @Component
- public 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, 会打印系统时间.
最后
以上, 就把 Spring Boot 整合定时任务简单介绍完了, 是不是特别简单, 下一篇我会介绍 Spring boot 的异步任务.
来源: https://www.cnblogs.com/zhangweizhong/p/12539921.html