首先在配置文件头部的必须要有:
<xmlns:task="http://www.springframework.org/schema/task"/>
其次xsi:schemaLocation必须为其添加:
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
然后spring扫描过程必须涵盖定时任务类所在的目录: 加上定时任务类所在包,我的是在common下
-
<context:component-scan base-package="com.**.service,com.**.common"> <!-- 去掉controller扫描 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
com.xx.common属于定时任务类的父级甚至更高级
然后设置动作启用定时任务
<task:annotation-driven/>
最后设置任务类
@Component @EnableAsync @EnableScheduling public class BloodTimer { @Autowired private UserServive userServive; /** * 定时任务,读取设备数据 */ @Scheduled(fixedDelay = 1 * 60 * 1000) @Async public void getPppeData() { try { System.out.println("执行了定时任务"); userService.getUser(); } catch (Exception e) { e.printStackTrace(); } } }