spring3_scheduler 任务调度

1.spring 定时任务在执行时会扫描需要定时的程序,此时程序内部不可出现未注入的方法及对象,由于(kof-servlet.xml)Controller只管控制器的注入,所以
会出现messageSource无法注入的错误。
例如:spring国际化问题。

在Controller中:private ReloadableResourceBundleMessageSource messageSource;

@Autowired
public void setMessageSource(final MessageSource messageSource) {
this.messageSource = (ReloadableResourceBundleMessageSource) ((DelegatingMessageSource) messageSource)
.getParentMessageSource();
}

如果没有定时任务,上面的代码是成立的。但是如果有定时任务配置,则建议改为(直接读配置文件的方式注入messageSource):
private final MessageSource messageSource = new FileSystemXmlApplicationContext(“根据自己的需要改:WEB-INF/applicationContext.xml”);
用法:messageSource.getMessage(....);

applicationContext.xml中:

<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
p:basename="classpath:messages">
<property name="defaultEncoding" value="utf-8" />
</bean>

2.task.xml(/WEB-INF/)
<?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:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.moshou.*"/><!-- 此处就是扫描全程序的配置,如果出现如上述国际化问题,则无法运行。 -->
<task:annotation-driven/>

</beans>
3.此时就可以在程序中加入定时任务了,只要有@Scheduled(。。。)的地方,程序可根据corn表达式进行定时任务。
package com.demo.common;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.demo.hero.service.HeroService;

/**
* 项目中的定时任务.
* @author netfishx
*
*/
@Component
public class CommonSchedule {

@Autowired
private HeroService heroService;

/**
* 每天早5点的定时任务.
*/
@Scheduled(cron = "0 0 5 * * ?")
public void dayTask() {
System.out.println("开始任务。。。");
}

/**
* 每小时一次的定时任务.
*/
@Scheduled(cron = "0 0 0/1 * * ?")
public void hourTask() {
heroService.update(heros.toArray(new Hero[0]));
}
}