- pom.xml 引入 web 依赖,需要用到 spring 的任务类
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 入口类上加@EnableScheduling注解,激活定时任务
@SpringBootApplication
@EnableScheduling
public class SchedulingApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingApplication.class, args);
}
}
- 类上加@Component注解,被扫描到。方法上加@Scheduled注解,设置定时
@Component
public class TestTask {
// 3秒一次
@Scheduled(fixedRate = 3000)
public void doing() {
System.out.println("3秒一次");
}
// 6 秒一次:秒 分 时 日 月 周
@Scheduled(cron = "*/6 * * * * *")
public void doing2() {
System.out.println("6秒一次");
}
}
参考:http://www.fengyunxiao.cn