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>
运行之后就可以自动执行了