SpringBoot实现定时器功能很简单,直接上代码
1.在启动类中标注@EnableScheduling注解,开启定时器功能
@SpringBootApplication @EnableScheduling //定时器 public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
2.写一个定时器类
@Component public class Scheduler { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Scheduled(cron="0 0/6 * * * ?") //每xx分钟执行一次 public void statusCheck() { logger.info("once every six minutes , start……"); Long start = System.currentTimeMillis(); //定时器要执行的代码 Long end2 = System.currentTimeMillis(); logger.info("end , " + "by time: " + (end2-start)/1000 + " second"); } }至此,就在SpringBoot中实现了定时器功能。但本人感觉,非必要条件下,定时器功能还是少用为妙,毕竟会消耗服务器资源。