SpringBoot定時器

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章