首先,我使用的是spring自带的定时器,因此,要在spring中配置
<!--添加标头-->
xmlns:util="http://www.springframework.org/schema/util"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.2.xsd"
<!--扫描定时器类所在的包 注意路径,我当时把cn落了-->
<context:annotation-config/>
<context:component-scan base-package="cn.com.trueway.xxtx.pojo"/>
<task:executor id="executor" pool-size="10"/>
<task:scheduler id="scheduler" pool-size="10"/>
<!-- 启用annotation方式 -->
<task:annotation-driven scheduler="scheduler" executor="executor" proxy-target-class="true"/>
<!--这个为了配置bean到xml-->
<bean id ="applicationContextUtil" class ="cn.com.trueway.xxtx.pojo.ApplicationContextUtil" ></bean >
配置结束
写定时器的类
package cn.com.trueway.xxtx.pojo;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import cn.com.trueway.xxtx.service.XxtxService;
@Component
@Lazy(false)
public class timetask {
private static Logger log = Logger.getLogger(timetask.class);
private XxtxService xxtxService;
//30秒执行一次 每个*号分别对应秒 分 时 天...
@Scheduled(cron="0/30 * * * * ?")
public void excute(){
log.warn("取期限还有一天的任务");
xxtxService = (XxtxService)ApplicationContextUtil.getBeans("xxtxService");
//执行service中的各种方法
}
}
由于定时器的注入优先级高于@Resource 和@Autowire
因此要换个注入方式
新建ApplicationContextUtil类
package cn.com.trueway.xxtx.pojo;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return context;
}
public static Object getBeans(String name) {
return getApplicationContext().getBean(name);
}
}
注意service上要有个注解
@Service("xxtxService")//标明service的名字,方便定时器的类中getbeans取
public class XxtxServiceImpl implements XxtxService {
亲测有效
至于
ERROR org.springframework.scheduling.support.MethodInvokingRunnable的原因
就是由于注入优先级的原因,找不到类,用上面的方法就能解决