2024-04-25 08:51

Spring Boot 实现定时任务

少尉

JavaEE

(15)

(0)

收藏

Spring Boot 要实现定时任务只要加 3 个注解就可以完成完成 只要分别在启动类,类,方法 加上

@EnableScheduling @Component @Scheduled 这三个注解缺一个都不行

1.在启动类加上 @EnableScheduling 注解

@EnableScheduling //定时任务在启动类注解
@SpringBootApplication
public class PulsApplication {
    public static void main(String[] args) {
        SpringApplication.run(PulsApplication.class, args);
    }
}

2.在需要设置定时任务的类上加 @Component 注解 ,在定时任务类里写需要执行的方法,然后在方法上加上 @Scheduled 注解并设置时间,这个方法就会在设定的时间里执行 

@Component //定时任务在类上的注解
public class TimeTask {
 
    /**
     * initialDelay 第一次启动任务延迟时间(单位 毫秒)
     * fixedRate    每次任务间隔时间 (单位 毫秒)
     */
    @Scheduled(initialDelay = 1000,fixedRate = 3000) //定时任务在方法上的注解
    public void timedA(){
        System.out.println("A 小熊369  "+new Date());
    }
 
    /**
     * cron 表达式 秒 分 时 天 月 年
     * cron = "10 44 21 * * ?" 表示每天 21点 44分 10秒 开始执行
     */
    @Scheduled(cron = "10 44 21 * * ?") //定时任务在方法上的注解
    public void timedB(){
        System.out.println("B 小熊369  "+new Date());
    }
}

@Scheduled 注解里一般设置时间有两种方式

一种是用 initialDelay 设置项目启动后延迟多少时间后执行和用 fixedRate 设置每次任务间隔时间,这种一般用于不需要准时准点时使用,例如每30分钟更新一下数据库,统计一下活跃数据等,如果有准时准点的要求用 cron 表达式会更好。

cron 表达式 一般用于准时统计,例如每个月 1号生成上一个月的月报,或者是凌晨时统计前一天的数据。

0条评论

点击登录参与评论