目标:实现springboot的简单的定时任务 工具:IDEA--2020.1 学习目标:实现springboot的简单的定时任务 本次学习的工程下载链接放到文本最后面
> package com.xmaven;
>
> import org.springframework.boot.SpringApplication; import
> org.springframework.boot.autoconfigure.SpringBootApplication; import
> org.springframework.scheduling.annotation.EnableScheduling;
>
> @SpringBootApplication //添加 @EnableScheduling 注解,开启对定时任务的支持
> @EnableScheduling
> public class SpringbootScheduledApplication {
>
> public static void main(String[] args) {
> SpringApplication.run(SpringbootScheduledApplication.class, args);
> }
>
> }
创建一个简单的任务类:
package com.xmaven.task;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component public class ScheduledTask {
@Scheduled(fixedRate = 3000)
public void scheduledTask(){
System.out.println("任务执行时间:" + LocalDateTime.now());
}
}
其中,常用的cron表达式有:
0 0 2 1 * ? * :表示在每月 1 日的凌晨 2 点执行
0 15 10 ? * MON-FRI :表示周一到周五每天上午 10:15 执行
0 15 10 ? 6L 2019-2020 :表示 2019-2020 年的每个月的最后一个星期五上午 10:15 执行
0 0 10,14,16 * * ? :每天上午 10 点,下午 2 点,4 点执行
0 0/30 9-17 * * ? :朝九晚五工作时间内每半小时执行
0 0 12 ? * WED :表示每个星期三中午 12 点执行
0 0 12 * * ? :每天中午 12点执行
0 15 10 ? * * :每天上午 10:15 执行
0 15 10 * * ? :每天上午 10:15 执行
0 15 10 * * ? * :每天上午 10:15 执行
0 15 10 * * ? 2019 :2019 年的每天上午 10:15 执行