項目中,許多地方都會用到定時器的功能, SpringBoot中也是有定時器的:html
1: 建立定時工具類:java
package com.gy.demo.common.config.task; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; /** * Description: 定時任務實現類 * 註釋: @Scheduled 定時器執行規則: @Scheduled(fixedRate = 6000) : 6秒執行一次 * @author geYang * @since 2017/12/26 **/ @Component public class SchedulerTask { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 6000) public void reportCurrentTime() { System.out.println("如今時間:" + dateFormat.format(new Date())); } }
2: 使用時在啓動類中聲明:git
package com.gy.demo; import org.mybatis.spring.annotation.MapperScan; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; /** * 項目啓動類 * 註解: @EnableScheduling 啓動項目時開啓定時任務 * * @author geYang */ @EnableScheduling @SpringBootApplication public class DemoApplication { private static org.slf4j.Logger logger = LoggerFactory.getLogger(DemoApplication.class); public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); logger.info("項目啓動成功!"); } }
參考大神: http://www.cnblogs.com/ityouknow/category/914493.htmlspring
項目源碼: https://gitee.com/ge.yang/SpringBootmybatis