参考网址
https://www.tianmaying.com/tutorial/spring-scheduling-task
要点1--定时任务上加@Scheduled注解(类上加@Component注解)
自动任务方法上加@Scheduled注解,注解后面加定时任务的定时。
/**
*
* Description:定时任务示例
*
*/
@Component
public class ScheduledTask {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private Integer count0 = 1;
private Integer count1 = 1;
private Integer count2 = 1;
/**
*
* Description:表示每隔5000ms,Spring scheduling会调用一次该方法,不论该方法的执行时间是多少
* @throws InterruptedException
*/
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() throws InterruptedException {
System.out.println(String.format("---第%s次执行,当前时间为:%s", count0++, dateFormat.format(new Date())));
}
/**
*
* Description:表示当方法执行完毕5000ms后,Spring scheduling会再次调用该方法
* @throws InterruptedException
*/
@Scheduled(fixedDelay = 5000)
public void reportCurrentTimeAfterSleep() throws InterruptedException {
System.out.println(String.format("===第%s次执行,当前时间为:%s", count1++, dateFormat.format(new Date())));
}
//一种通用的定时任务表达式,这里表示每隔5秒执行一次
@Scheduled(cron = "*/5 * * * * * *")
public void reportCurrentTimeCron() throws InterruptedException {
System.out.println(String.format("+++第%s次执行,当前时间为:%s", count2++, dateFormat.format(new Date())));
}
}
要点2--几种定时的表示方法
在@Scheduled注解中,我们使用了三种方式来实现了同一个功能:每隔5秒钟记录一次当前的时间:
fixedRate = 5000表示每隔5000ms,Spring scheduling会调用一次该方法,不论该方法的执行时间是多少。
fixedDelay = 5000表示当方法执行完毕5000ms后,Spring scheduling会再次调用该方法。
cron = "*/5 * * * * * *"提供了一种通用的定时任务表达式,这里表示每隔5秒执行一次。
要点3--main方法上加@EnableScheduling注解
main上加@EnableScheduling注解,说明要开启SpringBoot的自动任务。
@EnableScheduling 注解的作用是发现注解@Scheduled的任务并后台执行。
@RestController
@SpringBootApplication(exclude = SpringDataWebAutoConfiguration.class)
@EnableScheduling
public class RuicheServerJSP {
@RequestMapping("/")
String index(){
return "Hello Spring Boot";
}
public static void main(String[] args){
SpringApplication.run(RuicheServerJSP.class, args);
}
}
★@Scheduled中cron一些常用的表达式
"0 0 12 * * ?" 每天中午十二点触发
"0 15 10 ? * *" 每天早上10:15触发
"0 15 10 * * ?" 每天早上10:15触发
"0 15 10 * * ? *" 每天早上10:15触发