定时任务SpringBoot默认已经帮我们实行了,只需要添加相应的注解就可以实现。
SpringBoot整合定时任务其实就两点:
1.创建一个能被定时任务类,方法上加入@Scheduled注解
2.在启动类application上加入@EnableScheduling注解
只需要引入 Spring Boot Starter 包即可
application类启用定时4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.6.RELEASE com.huzh springboot-scheduled 0.0.1-SNAPSHOT springboot-scheduled springboot-scheduled UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-devtools runtime org.springframework.boot spring-boot-maven-plugin
在启动类上面加上@EnableScheduling即可开启定时
@SpringBootApplication
@EnableScheduling
public class SpringbootScheduledApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootScheduledApplication.class, args);
}
}
创建定时任务类TestTimer
- @Component注解表明一个类会作为组件类,并告知Spring要为这个类创建bean。
- @Scheduled开启定时
@Component
public class TestTimer {
@Scheduled(cron = "0/1 * * * * ?")
private void test() {
System.out.println("执行定时任务的时间是" + new Date());
}
}
备注
需要注意的是@Scheduled(cron = “0/1 * * * * ?”)中cron的值根据自己实际需要去写,可参考http://cron.qqe2.com/



