定时任务quartz
一,使用Quartz实现定时任务
1)依赖
<!-- 定时任务开始 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>3.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>1.8.5</version> </dependency> <!-- 定时任务结束-->
二,配置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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <!-- 定时任务 --> <!-- 任务1 --> <bean name="quartzTest" class="top.heyuantao.manager.controller.Task" /> <bean id="quartzTestJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="quartzTest"></property> <property name="targetMethod" value="test"></property> <property name="concurrent" value="false"></property> </bean> <!-- 任务1指定策略 --> <bean id="quartzTestTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="quartzTestJob"/> <!-- 每十秒执行一次 --> <property name="cronExpression" value="0/10 * * * * ?"></property> </bean> <!-- 任务2 --> <bean name="quartzmain" class="top.heyuantao.manager.controller.Task" /> <bean id="quartzmainJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="quartzTest"></property> <property name="targetMethod" value="main"></property> <property name="concurrent" value="false"></property> </bean> <!-- 任务2指定策略 --> <bean id="quartzmainTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="quartzmainJob"/> <!-- 每五秒执行一次 --> <property name="cronExpression" value="0/5 * * * * ?"></property> </bean> <!-- 启动触发器的配置 --> <bean name="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref local="quartzTestTrigger" /> <ref local="quartzmainTrigger" /> </list> </property> </bean> </beans>
三,任务
package top.heyuantao.manager.controller;
import top.heyuantao.manager.utli.Time;
public class Task {
public void test() {
System.out.println("任务1执行中"+"---------->"+Time.getTime());
}
public static void main(String[] args) {
System.out.println("任务2执行中"+"---------->"+Time.getTime());
}
}
四,效果
http://cron.qqe2.com/