Spring Boot 默认已经实现了定时任务,只需要添加相应的注解即可完成
pom.xml 文件配置
pom.xml 不需要添加其他依赖,只需要加入 Spring Boot 依赖即可,这里我们添加一个 web 和 test 的依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
在启动类上面加上 @EnableScheduling 注解
在启动类上面加上 @EnableScheduling 注解即可开启定时任务
@EnableScheduling
@SpringBootApplication
public class SchedulingApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingApplication.class, args);
}
}
编写定时任务
@Component
public class ScheduledTask {
@Scheduled(initialDelay=1000, fixedDelay = 1000)
public void task1() {
System.out.println("延迟1000毫秒后执行,任务执行完1000毫秒之后执行!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Scheduled(fixedRate = 2000)
public void task2() {
System.out.println("延迟1000毫秒后执行,之后每2000毫秒执行一次!");
}
}
除了这些还支持 cron 表达式
@Scheduled(cron = "*/2 * * * * ?")
public void task3() {
System.out.println("每2秒执行一次!");
}
举几个例子
*/2 * * * * ? 表示每2秒执行一次!
0 0 2 1 * ? * 表示在每月的1日的凌晨2点调度任务
0 15 10 ? * MON-FRI 表示周一到周五每天上午10:15执行作业
0 15 10 ? 6L 2002-2006 表示2002-2006年的每个月的最后一个星期五上午10:15执行作
推荐一个 cron 表达式在线生成工具
http://cron.qqe2.com/