业务方法类
Java代码
package com.task;
/**
* 业务方法
*
*/
public class TestJob {
public void execute() {
try {
System.out.println("我的业务方法被调用了---------!");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
配置文件beans.xml
Java代码
<?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:context="http://www.springframework.org/schema/context"
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/tx http://www.springframework.org/schema/tx/spring-tx-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/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 普通的业务Bean -->
<bean id="testJob" class="com.task.TestJob" />
<!-- 触发器 -->
<bean
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="testTrigger" />
</list>
</property>
<property name="autoStartup" value="true" />
</bean>
<bean id="testTrigger"
class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="testJobDetail" />
<!-- 每隔1秒钟触发一次 -->
<property name="cronExpression" value="*/1 * * * * ?" />
</bean>
<!-- 计划 -->
<bean id="testJobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="testJob" />
<property name="targetMethod" value="execute" />
<!-- 是否允许任务并发执行。当值为false时,表示必须等到前一个线程处理完毕后才再启一个新的线程 -->
<property name="concurrent" value="false" />
</bean>
</beans>
测试方法
Java代码
package com.task;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 测试类
*
*/
public class Test {
public static void main(String[] args) {
try {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("com/task/beans.xml");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Main方法执行开始了! 定时器伴随着Spring的初始化执行了。。。");
System.out.println("Main方法执行结束了!");
}
}
我在运行调试的时候遇到了一些错误,比如:
Java代码
Error creating bean with name 'testJobDetail' defined in class path resource [com/task/beans.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/collections/SetUtils
这个错误是因为工程中缺少必要的commons-collections-3.2.1.jar包引起的,另外必须的jar包还有quartz-1.6.4.jar,spring.jar,commons-logging.jar