`

通过quartz框架实现简单的定时调度任务

    博客分类:
  • jsp
阅读更多

       这期的项目需要用到定时调度,刚听到这个词(卧擦,这么牛逼,怎么做?),项目经理又补了一句,就是定时任务(原来是定时任务,惨汗~我心里就在想了那不就是timer吗?),任务分配下来了,开工了!

 

       以前只写过简单的定时任务,不免心里没底,就百度了下。发现java实现定时调度任务的方法差不多有三种:第一,timer类实现。第二,ScheduleExecutorService。第三,spring+quartz。timer虽然不需要其他的jar包支持,但是timer实现的调度是单线程,并且灵活性不够,还有就是产生异常时,timer的调度任务会停止!第二种方法虽然不会存在timer类的缺陷,但是实现起来比较麻烦。最后我选择了第三种方法,一是因为我参与的项目是spring框架支持的。而是实现起来也比较容易,嘿嘿~

       

        通过spring+quartz实现定时调度,首先在spring的配置文件加入如下的代码

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
            
        <!-- 要调用的工作类 -->
        <bean id="quartzJob" class="com.QuartzJob"></bean>
        <!-- 定义调用对象和调用对象的方法 -->
        <bean id="jobtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
            <!-- 调用的类 -->
            <property name="targetObject">
                <ref bean="quartzJob"/>
            </property>
            <!-- 调用类中的方法 -->
            <property name="targetMethod">
                <value>work</value>
            </property>
        </bean>
        <!-- 定义触发时间 -->
        <bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerBean">
            <property name="jobDetail">
                <ref bean="jobtask"/>
            </property>
            <!-- cron表达式 -->
            <property name="cronExpression">
                <value>10,15,20,25,30,35,40,45,50,55 * * * * ?</value>
            </property>
        </bean>
        <!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序  -->
        <bean id="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
            <property name="triggers">
                <list>
                    <ref bean="doTime"/>
                </list>
            </property>
        </bean>
	
</beans>

 再写个需要调度的方法,如下:

package com;

import java.util.Date;

public class QuartzJob {
	
	public void work(){
		System.out.println(new Date().toLocaleString()+"Quartz的任务调度!!!");
	}
	
}

 这样就实现了简单定时调度任务了!

 

       

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics