---
title: "spring 定时任务"
author: "vinceyu"
date: "2011-01-28T09:01:52Z"
tags: ["Spring", "quartz"]
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2011-11-24T14:01:29Z"
id: 898652
url: "https://vinceyu.iteye.com/blog/898652"
---

定时任务类：

 

```
public class TimerTask {
	public void exeTask() {
		System.out.println("exeTask");
	}
}
```

 配置定时任务task.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: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.5.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- 被调用的定时任务类也可以是接口 -->
	<bean id="task" class="com.test.task.TimerTask">
	</bean>

	<!-- 定义调用对象和调用对象的方法 -->
	<bean id="exeTask"
		class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">

		<!-- 调用的类 -->
		<property name="targetObject" ref="task" />

		<!-- 调用类中的方法 -->
		<property name="targetMethod" value="exeTask" />

		<!-- 是否允许任务并发执行。当值为false时，表示必须等到前一个任务处理完毕后才再启一个新的任务 -->
		<property name="concurrent" value="false" />
	</bean>

	<!-- 定义触发时间 -->
	<bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerBean">
		<!--
			因为属性jobDetail的引用只能是jobDetail类型的对象，所以通过MethodInvokingJobDetailFactoryBean来转换
		-->
		<property name="jobDetail" ref="exeTask" />
		<!-- cronExpression表达式 ，"0 30 1 * * ?"表示每天凌晨1:30触发任务-->
		<property name="cronExpression" value="0 30 1 * * ?" />
	</bean>

	<!-- 总管理类 如果将lazy-init='false'，那么容器启动就会执行调度程序  -->
	<bean id="startQuertz" lazy-init="false" autowire="no"
		class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="doTime" />
			</list>
		</property>
		<property name="autoStartup" value="true" />
		<property name="schedulerName" value="cronScheduler" />
	</bean>
</beans>
```

 web.xml配置：

```
        <listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:config/task.xml</param-value>
	</context-param>
```

 

  可能出现异常：

 

```
 java.lang.ClassNotFoundException: org.quartz.JobDetail
```

   异常原因是因为没有导入quartz-1.5.0.jar，导入即可。