用spring+maven写了个简单的定时任务,主要在配置,配置完也就基本完成任务了:
maven配置:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>my.spring.study</groupId>
<artifactId>scan.aop</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.11</version>
</dependency>
</dependencies>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- 定义具体任务-->
<bean id="myJobDetail" class="com.along.apple.quartz.QuartzTest"></bean>
<!-- 指定要执行的定时任务类,这里-->
<bean id="myJobQuartz" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="myJobDetail"/>
<property name="targetMethod" value="testQuartz"/>
<!--false表示等上一个任务执行完后再开启新的任务 -->
<property name="concurrent" value="false"/>
</bean>
<!-- 触发器:定义触发时间和要运行的实体-->
<bean id="myJobCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="myJobQuartz"/>
<property name="cronExpression" value="0/5 * * * * ?"/>
</bean>
<!-- 调度器:开启定时任务,注册定时器实体 集合 -->
<bean id="myJobScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="myJobCronTrigger"/>
</list>
</property>
<property name="autoStartup" value="true"/>
</bean>
</beans>
测试类及效果图,主要是加载完配置文件,初始化bean工厂后,定时任务就会执行:
public class QuartzTest {
int i = 0;
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config*.xml");
}
public void testQuartz() {
System.out.println("第" + i + "次执行定时任务");
i++;
}
}
其实主要在配置,我就实现类一个类QuartzTest.java,运行该类的main方法,读取spring配置文件,初始化spring容器、bean工厂,可以自动触发定时任务的执行(因为已经设置:<property name="autoStartup" value="true"/>)