@Scheduled
@Scheduled是Spring框架的定时任务实现,相比JDK的ScheduledThreadPool功能更加强大。可以先创建一个Spring Boot项目,在启动类上添加@EnableScheduling注解,使@Scheduled生效,开启定时任务:
@SpringBootApplication
@EnableScheduling
public class LearnSpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(LearnSpringbootApplication.class, args);
}
}
这里我们重点看使用@Scheduled的cron属性定义定时任务的时间表达式,它的功能更加丰富。先看一个简单的例子:
@Service
public class ScheduleService {
...................
/**
* 每天晚上23:59执行一次
*/
@Scheduled(cron = "0 59 23 * * ?")
public void task3() {
logger.info("task3-start");
sleep(6);
logger.info("task3-end");
}
...................
}
*在启动类添加@EnableScheduling注解, 在任意类中写一个@Scheduled(cron = "0 59 23 * * ?")方法就可以