平常工作中也有接触到定时任务,刚刚接触时自己也是在网上学习了一下。然后今天想记录下来我的。
定时任务类:
public class TaskTest {
public void print(){
String time = DateFormat.getDateTimeInstance().format(new Date());
System.out.println("定时器触发打印--print"+time);
}
}
applicationContext.xml配置:
<?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-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.2.xsd"
default-lazy-init="false">
<!-- 配置任务bean类 -->
<bean id="TaskTest" class="timeTask.TaskTest"></bean>
<!-- 配置方法映射工厂类 -->
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="TaskTest"></property>
<property name="targetMethod" value="print"></property>
<property name="concurrent" value="false"></property>
<!-- concurrent : false表示等上一个任务执行完后再开启新的任务 -->
</bean>
<!-- 配置任务高度的的时间/周期 -->
<bean id="billsCheckJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="jobDetail"></property>
<property name="cronExpression" value="0/5 * * * * ?"></property>
</bean>
<!-- 调度工厂 -->
<bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="billsCheckJobTrigger"/>
</list>
</property>
</bean>
</beans>
web.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
jar包结构:
然后Tomcat加载项目并且运行项目,控制台输出如下: