Spring注解已经用了一段时间,但是在实现定时器的时候还是遇到了一些问题,主要还是XML的问题,没有引入spring task的schema;这里记录一下。
Spring的定时注解主要分两步:
1. 创建task的xml,引入spring的task schema,并配置好task所在的package,spring会自动扫描该package下所有注解的类和注解的方法;
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"> <context:component-scan base-package="com.xx.schedule" /> <task:annotation-driven/> </beans>
2. 创建相应的task类,为方法设置@Scheduled
package com.xx.schedule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* 计息定时器
* @author kinfer
*
*/
@Component
public class WorkerScheduler {
private static final Logger log = LoggerFactory.getLogger(WorkerScheduler.class);
@Autowired
private InterestCalculationWorker interestCalcWorker;
@Scheduled(cron="59 30 23 * * ?")
public void scheduleInterestCalc(){
log.debug("schedule to calc checking acct interest");
interestCalcWorker.calcCheckingAcctInterest();
}
}
这里的@Scheduled(cron="59 30 23 * * ?") 表示每天的23:30:59执行,cron表达式可以到网上找相关的资料。