前言
在最近的面试中,面试官问到了定时器相关的知识,这里总结一下,在实际开发中,很多时候都会需要用到定时任务,能够自动执行所需要执行的方法,下面我介绍下在Springboot中如何配置定时任务。
开启定时任务
package com.ljh.springbootschedule.controller;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
@EnableScheduling
public class scheduleController {
@Async
@Scheduled(cron = "0/5 * * * * ?")
public void scheduleDemo(){
System.out.println("执行第一个定时器..."+ LocalDateTime.now().toLocalTime());
System.out.println();
}
@Async
@Scheduled(cron = "0/6 * * * * ?")
public void scheduleDemo1(){
System.out.println("执行第二个定时器..."+ LocalDateTime.now().toLocalTime());
System.out.println();
}
}
其中@Scheduled(cron = “0/5 * * * * ?”)这个注解的 cron参数对应着 秒 分 时 日 月 年
具体参数规则如下

示例:
表达式 | 意义 |
---|
每隔5秒钟执行一次 | */5 * * * * ? | 每隔1分钟执行一次每天1点执行一次 | 0 * /1 * * * ? | 每天23点55分执行一次 | 0 55 23 * * ? | 每月最后一天23点执行一次 | 0 0 23 L * ? | 每周六8点执行一次 | 0 0 8 ? * L | 每月最后一个周五,每隔2小时执行一次 | 0 0 */2 ? * 6L | 每月的第三个星期五上午10:15执行一次 | 0 15 10 ? * 5#3 | 在每天下午2点到下午2:05期间的每1分钟执行 | 0 0-5 14 * * ? | 表示周一到周五每天上午10:15执行 | 0 15 10 ? * 2-6 |
结果:

测试完成,大家来自己动手试试吧。
|