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中實現了定時器功能。但本人感覺,非必要條件下,定時器功能還是少用爲妙,畢竟會消耗服務器資源。