spring boot項目需要在啟動類加上注解 @EnableScheduling
定義一個接口
StockTask.java
1 public interface StockTask { 2 public void task() ; 3 }
定義一個實現類
並繼承上面代碼
@Component public class StockTaskImpl implements StockTask { /** * 定時器 * @throws IOException */ @Scheduled(fixedRate=30000) @Override public void task() { System.err.println("每30s執行一次"); } }
如果是Spring的項目需要配置一下bean
<beans xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"> <!--開啟這個配置,spring才能識別@Scheduled注解 --> <task:annotation-driven scheduler="qbScheduler" mode="proxy"/> <task:scheduler id="qbScheduler" pool-size="10"/> <!-- 自動掃描包(也就是自己添加的定時器路徑) --> <context:component-scan base-package="com.dj.dao,com.dj.service" /> </beans>
運行之后就可以自動執行了