**
介绍
**
Spring Task是Spring3.0以后自主开发的定时任务工具;
可以将它比作一个轻量级的Quartz,而且使用起来很简单,除spring相关的包外不需要额外的包;
而且支持注解和配置文件两种形式;
类似工具:
- Timer:Java自带,来自 java.util.Timer类 java.util.TimerTask类(不推荐,因为不能设置时间)
- Quartz 第三方框架,开源,功能强大;(使用起来稍显复杂,企业中用得多)
- Spring Task:Spring3.0后自带了Task调度工具,比Quartz更简单方便,但功能不会减少;
定时任务 :某个功能需要在指定频率中运行;
比如:每天凌晨备份下数据;每个月清空日志;投放的广告在固定时间过期;每三个月清空一次Cookie;
实战 on Spring Boot
——————————————
实现定时任务:
1.XML;
2.注解;
下面是注解方式:
POM:
org.springframework spring-context<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
添加配置
注解 或者 XML;
本Springboot项目采用注解:@EnableScheduling
SpringtaskApplication
@EnableScheduling
@ComponentScan
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class SpringtaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringtaskApplication.class, args);
}
}
MyTask
@Component
public class MyTask {
@Scheduled(initialDelay = 1000,fixedDelay = 1000) // 表示Tomcat启动后,等1s再执行他,每隔1s执行一次
public void firstTask(){
System.out.println(new Date() + “这是第1个定时任务。”);
}
@Scheduled(cron="*/5 * * * * ?") // 每隔5s执行一次
public void secondTask(){
System.out.println(new Date() + “这是第2个定时任务。”);
}
}
输出:
Thu May 30 20:27:46 CST 2019这是第1个定时任务。
Thu May 30 20:27:47 CST 2019这是第1个定时任务。
Thu May 30 20:27:48 CST 2019这是第1个定时任务。
Thu May 30 20:27:49 CST 2019这是第1个定时任务。
Thu May 30 20:27:50 CST 2019这是第2个定时任务。
Thu May 30 20:27:50 CST 2019这是第1个定时任务。
Thu May 30 20:27:51 CST 2019这是第1个定时任务。
Thu May 30 20:27:52 CST 2019这是第1个定时任务。
Thu May 30 20:27:53 CST 2019这是第1个定时任务。
Thu May 30 20:27:54 CST 2019这是第1个定时任务。
CRON表达式
关于cron表达式,如果不去理解?很容易被用错
每一位表示的是 [秒 分 时 日 月 周 年]
The ‘?’ character is allowed for the day-of-month and day-of-week fields. It is used to specify ‘no specific value’. This is useful when you need to specify something in one of the two fields, but not the other.
注意着两个概念 day-of-month /day-of-week
CRON表达式 含义
"0 0 12 * * ?" 每天中午十二点触发
"0 15 10 ? * *" 每天早上10:15触发
"0 15 10 * * ?" 每天早上10:15触发
"0 15 10 * * ? *" 每天早上10:15触发
"0 15 10 * * ? 2005" 2005年的每天早上10:15触发
"0 * 14 * * ?" 每天从下午2点开始到2点59分每分钟一次触发
"0 0/5 14 * * ?" 每天从下午2点开始到2:55分结束每5分钟一次触发
"0 0/5 14,18 * * ?" 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发
"0 0-5 14 * * ?" 每天14:00至14:05每分钟一次触发
"0 10,44 14 ? 3 WED" 三月的每周三的14:10和14:44触发
"0 15 10 ? * MON-FRI" 每个周一、周二、周三、周四、周五的10:15触发