spring定時任務開啟步驟
首先在配置文件頭部的必須要有:
<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(); } }
/** * 定時任務,定時刪除操作日志 * 每天6點執行一次,刪除2年前日志,只保留近2年日志 */ @Scheduled(cron = "0 0 6 * * ?") public void deleteLog() { try { System.out.println("執行了定時刪除日志信息"); logMessageService.deleteLogTimer(); } catch (Exception e) { e.printStackTrace(); } }
}

浙公網安備 33010602011771號