1. 功能介绍
应用中的定时任务,SpringBoot的内置任务,一个注解可以开启定时任务。
2.用法
maven依赖 pom.xml 文件
<dependencies>
<dependency>
<groupId> org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId> org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId> org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
使用
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import com.taobao.pandora.boot.PandoraBootstrap;
@SpringBootApplication
@EnableScheduling
public class Application{
public static void main(String[] args) {
PandoraBootstrap.run(args);
SpringApplication.run(Application.class, args);
PandoraBootstrap.markStartupAndWait();
}
}
注解
@Component
public class ScheduleTask{
@Scheduled(cron="0 2 * * * *")
public void cronTask() throws Exception{
System.out.println("cron time:"+new Date(System.currentTimeMillis()));
}
}
3.参数
3.1 cron
定义时间表达式,它包含了六或七个域:
Seconds : 可出现", - * /“四个字符,有效范围为0-59的整数
Minutes : 可出现”, - * /“四个字符,有效范围为0-59的整数
Hours : 可出现”, - * /“四个字符,有效范围为0-23的整数
DayofMonth : 可出现”, - * / ? L W C"八个字符,有效范围为0-31的整数
Month : 可出现", - * /“四个字符,有效范围为1-12的整数或JAN-DEc
DayofWeek : 可出现”, - * / ? L C #“四个字符,有效范围为1-7的整数或SUN-SAT两个范围。1表示星期天,2表示星期一, 依次类推
Year : 可出现”, - * /"四个字符,有效范围为1970-2099年
下面简单举几个例子:
“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触发
3.2 fixedRate
该属性的含义是上一个调用开始后再次调用的延时(不用等待上一次调用完成),这样就会存在重复执行的问题。单位 毫秒
3.3 fixedDelay
该属性的功效与上面的fixedRate则是相反的,配置了该属性后会等到方法执行完成后延迟配置的时间再次执行该方法。 单位 毫秒