二.使用idea 整合springmvc和Quartz实现定时任务

1.在pom.xml 配置的依赖quartz

<!--quartz-->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.0</version>
        </dependency>

2.在Web项目web.xml中配置quartz配置文件加载路径


3.添加定时调度的任务类,打印时间

package com.ivy.quartz;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * Created by Administrator .
 */
public class FirstQuartzTest {

    private int num=1;

    public void  test(){
        System.out.println("now time is:"+
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        System.out.println(num);
        num++;
    }
}

4.在quartz配置文件spring-quartz.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <!-- 添加调度的任务bean 配置对应的class-->
    <bean id="firstQuartzTest" class="com.ivy.quartz.FirstQuartzTest" />
    <!-- 使用MethodInvokingJobDetailFactoryBean,,通过targetMethod指定调用方法-->
    <bean id="springQtzJobMethod" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject">
            <ref bean="firstQuartzTest"/>
        </property>
        <property name="targetMethod">
            <value>test</value>  <!-- 要执行的方法名称 -->
        </property>
    </bean>
    <!-- ======================== 调度触发器 ======================== -->
    <bean id="CronTriggerBean" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="springQtzJobMethod"></property>
        <property name="cronExpression" value="2 * * * * ?"></property>
    </bean>

    <!-- ======================== 调度工厂 ======================== -->
    <bean id="SpringJobSchedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="CronTriggerBean"/>
            </list>
        </property>
    </bean>
</beans>

5.运行tmocat进行测试,在第2秒的时候进行输出


参考资料:http://djkin.iteye.com/blog/1714323

猜你喜欢

转载自blog.csdn.net/ivylingling123/article/details/80043041