SpringBoot中定时任务比较简单,就2个步骤:
1. 通过@EnableScheduling激活上下文中的所有定时任务;
2. 通过@Scheduled标注某个方法为定时任务。
实例:
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
public class AdminScheduleTasksConfig {
}
@Component
public class UserScheduleTaskTest {
@Autowired
private UserService userService;
/**
* 用户数任务:每5分钟执行1次
*/
@Scheduled(cron = "0 0/5 * * * ?")
public void calUserCntTask() {
Integer userCnt = userService.calUserCnt();
}
}
本文介绍如何使用SpringBoot实现简单的定时任务。通过@EnableScheduling开启定时任务支持,并使用@Scheduled注解定义具体任务及其执行频率。
2266

被折叠的 条评论
为什么被折叠?



