试上Spring的scheduledTask: 不应该出有关问题的有关问题
要用Spring的scheduledTask了,
于是先在eclipse里做了小试验,试下.本来很简单的一个功能,不论是spring的文档还是网上都有可以参考的小例子, 但一试,发现有问题了.
一是配置的那个scheduledTask没有运行, 后来用一个很笨的方法运行了, 但时间明显不对.
下面是运行程序的main方法:
public static void main(String[] args) throws InterruptedException {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
int i=0;
while(i< 10) {
Thread.sleep(1000);
System.out.println("..."+i++);
}
if("run".equals(args[0])) {
System.out.println("timerFactory: "+context.getBean("timerFactory"));
}
}
那
个很笨的方法是通过启动参数来运行,也就是若以这样的方式(java -jar springScheduler.jar
run)来运行时,那个scheduledTask就可以起作用了. 若不加run,而以"java -jar
springScheduler.jar"来运行的话, scheduledTask就不起作用?
不应该呀!
下面是applicationContext.xml里的配置:
<bean id="checkEmail" class="spring.MyTimerTask"/>
<bean id="scheduledTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="delay" value="0" />
<property name="period" value="5" />
<property name="timerTask" ref="checkEmail" />
</bean>
<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<!-- see the example above -->
<ref bean="scheduledTask" />
</list>
</property>
<!--<property name="daemon" value="true"/>-->
</bean>
觉得原因是Spring在初始化context时没有初始化timerFactory,这样若不通过context来getBean
("timerFactory")的话, 这个实例就不会初始化,
总觉得不应该这样的.一般一个scheduledTask的运行用户是不会有干涉的,
所以也不必为了让这个timerFactory初始化而特意get下bean.
考虑到这个原因后<beans>的属性里加上了default-lazy-init="false",但还是不行, 如下所示:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"
default-lazy-init="false">
这是为什么? 怎么解决? 从网上搜了很多这方面的材料但都没提到这个问题, 我为什么一到我这就出问题了呢?
再说第二个问题: 时间明显不对.
为了明显点, 我特意把每执行一次的时间改为5ms, 如下所示:
<property name="delay" value="0" />
<property name="period" value="5" />
这样不用等待就立即执行,但当用"java -jar springScheduler.jar run"方式启动后,运行的很慢,我的电脑不至于那么慢吧?
这里面又有什么隐情? 中邪了???
----------------------------------------
下载这里的jar包,可能运行"java -jar springScheduler.jar run"(或不带run参数)来试试.
public static void main(String[] args) throws InterruptedException {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
context.getBean("timerFactory");
}
2- timer is legacy now,it's single-threaed, so if your task takes a long time to run, later ones will be delayed. try to use quartz or DelayedQueue in Java5 or other solutions.
但别人怎么没遇到这个问题呢, 在网上也没搜到这方面的说明.