一:在web.xml文件中添加对容器启动的监听, 当容器启动后将自动装配application-job.xml文件
<!-- 为上下文参数(相当于全局变量)contextConfigLocation赋值,该配合指向application开头的xml文件, 定时任务的配置文件 application-job.xml也将被读取 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application*.xml</param-value>
</context-param>
<!-- 对web容器启动进行监听,当容器启动后将自动装配上下文变量contextConfigLocation指向的配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
二:配置application-job.xml文件
注意在<beans>节点中配置xmlns:task和xsi:schemaLocation关于task的属性值
<?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: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/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">
<description>Job Config</description>
<!-- 扫描定时器所在的包路径 -->
<context:component-scan base-package="org.power.quickbuy.job" />
<!-- 配置定时任务 -->
<task:scheduled-tasks>
<task:scheduled ref="alertJob" method="execute" cron="0 0 9 * * ?" />
</task:scheduled-tasks>
<task:scheduled-tasks>
<task:scheduled ref="statisticsJob" method="execute" cron="0 0 1 * * ?" />
</task:scheduled-tasks>
</beans>
三: 创建定时任务的类及方法
注意: 类头部需要@Service注解
package org.power.quickbuy.job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service("alertJob")
public class AlertJob {
private static Logger logger = LoggerFactory.getLogger(AlertJob.class);
public void execute(){
logger.info("当前时间:[{}]", System.currentTimeMillis());
}
}
四:定时器配置中的时间表达式请参照如下网址: http://blog.csdn.net/javaecrainbow/article/details/8998291