定时任务
项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。 Spring为我们提供了异步执行任务调度的方式,提供TaskExecutor 、 TaskScheduler 接口。
使用@EnableScheduling与@Scheduled完成定时任务
(1)@EnableScheduling开启基于注解的定时任务
package com.kuake.spingboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling//开启基于注解的定时任务
@SpringBootApplication
public class SpingbootAsyncApplication {
public static void main(String[] args) {
SpringApplication.run(SpingbootAsyncApplication.class, args);
}
}
(2)@Scheduled来定制定时任务
/**
* second minute, hour, day of month, month , day of week, (year)
* <p>E.g. {@code "0 * * * * MON-FRI"}
*/
@Scheduled(cron = "0-10 * * * * *")
public void myTask(){
System.out.println("hello==========>当前的线程"+Thread.currentThread().getName());
}
输出结果:
2019-06-12 15:36:32.281 INFO 8752 --- [ main] s.a.ScheduledAnnotationBeanPostProcessor : No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
2019-06-12 15:36:32.329 INFO 8752 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2019-06-12 15:36:32.334 INFO 8752 --- [ main] c.k.s.Spingboot04AsyncApplication : Started Spingboot04AsyncApplication in 5.596 seconds (JVM running for 7.434)
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
hello==========>当前的线程pool-1-thread-1
上面@Scheduled配置的cron = 0-10 * * * * *
,代表每一分钟的0-10秒执行。现在来介绍一下cron表达式:
cron
表达式由7个部分组成,各部分用空格隔开。每个部分代表的含义从左到又分别是 second
minute
, hour
, day of month
, month
, day of week,
(year)
,最后一个位置年可以省略不写。
也可以使用一些符号来方便我们表达:
字段 | 合法值 | 范围 |
---|---|---|
秒 | 0-59 | ,-*/ |
分 | 0-59 | ,-*/ |
时 | 0-23 | ,-*/ |
天 | 1-31 | ,-*/ L W C |
月 | 1-12 | ,-*/ |
周 | 0-7或者 SUN-SAT | ,-*/ L C # |
符号 | 意义 |
---|---|
, | 枚举 |
× | 整个时段 |
/ | 步长(就是每隔多少) |
L | 最后 |
C | 工作日 |
# | 星期 (3#2 第三个星期二) |
举例个子:
0 0/3 11,12 * * ?
每个月的每一天的 11点 12点 每隔三分钟执行一次
0 0 2-4 ? * 3#1
每个月的 第三周的周一 2 点 到4点 整点执行。