Quartz是一个良好的任务调度中间插件
1. 引入spring和quartz的jar包
2. 创建定时任务类
package com.timeout;
import java.sql.Time;
/*
* 定时任务类
*/
public class StudentDay {
public void study(){
// 获取时间
Time time = new Time(System.currentTimeMillis());
// 执行任务
System.out.println(time+" : 学习中.........");
}
}
3. 配置spring注入Quartz
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
">
<!-- 注入定时任务类 -->
<bean id="stuDay" class="com.timeout.StudentDay"></bean>
<!-- 定义执行任务bean的类 -->
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!-- 配置调用的类 -->
<property name="targetObject" ref="stuDay"></property>
<!-- 配置执行的方法 -->
<property name="targetMethod" value="study"></property>
</bean>
<!-- 定义触发器 -->
<bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="jobDetail"></property>
<!-- 触发Corn时间表达式 -->
<property name="cronExpression" value="0/1 * * * * ?"></property>
</bean>
<!-- 启动类,执行触发器 -->
<bean id="starQuartz" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="doTime" />
</list>
</property>
</bean>
</beans>
4. 测试
package com.timeout;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/*
* 测试Quartz
*/
public class Test {
public static void main(String[] args) {
/*
* 加载Quartz配置文件xml,spring自动调用bean执行
*/
ApplicationContext ac = new ClassPathXmlApplicationContext("springQuartz.xml");
}
}