Spring 定時任務配置,Spring任務配置
1.applicationContext.xml 中 加入task 的聲明與xsd
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
配置中加入
<task:annotation-driven/>
這個是用來啟用自動的註解解析。
2.編寫POJO
@Component public class DailyPiracyJob { Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private AppInfoService appInfoService;@Scheduled(cron = "0 0 23 * * ?")public void scan() throws Exception {try {List<AppInfo> allAppList = appInfoService.selectAllAppInfo();if(null != allAppList && allAppList.size() > 0){for(AppInfo appInfo : allAppList){appInfoService.insertDailyPiracy(appInfo.getAppMd5());}}} catch (Exception e) {logger.error("error when Channel Monitoring.", e);}}}
@Compont 註解,是讓Spring context 可以掃描到,並自動注入需要的bean
@Scheudle 核心註解,不能有傳回值,cron是定義了任務啟動並執行間隔,具體,請參考網上其他教程
需要注意的是,在applicationContext.xml中不能啟用 default-lazy-init=“true”,否則註解會失效