Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1970003
  • 博文数量: 606
  • 博客积分: 9991
  • 博客等级: 中将
  • 技术积分: 5725
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-17 19:07
文章分类

全部博文(606)

文章存档

2011年(10)

2010年(67)

2009年(155)

2008年(386)

分类:

2008-11-11 20:37:52

用Quartz可以很轻松的实现定时的任务调度,使用Quartz之前需要添加jar包: quartz-1.6.1.jar 下载地址:

一、定时调度服务
1.xml文件 JobQuartz1.xml

xml version="1.0" encoding="UTF-8"?>
DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "">

<beans>
      

      
<bean id ="sjob" class="service.UserService"/>
    
      

      
<bean name="userJob" class="org.springframework.scheduling.quartz.JobDetailBean">
        
<property name="jobClass">
          
<value>schedule.TestJobvalue>  
        
property>
        
<property name="jobDataAsMap">  
          
<map>
            
<entry key="service"><ref local="sjob"/>entry>
          
map>
        
property>
      
bean>
    
    
    

    
<bean id = "cron" class = "org.springframework.scheduling.quartz.CronTriggerBean">
        
<property name="jobDetail">
            
<ref bean="userJob"/>
        
property>
        
<property name="cronExpression">
            
<value>0 0 15 * * ?value> 
        
property>
    
bean>
    
    

    
<bean autowire = "no" class = "org.springframework.scheduling.quartz.SchedulerFactoryBean">
        
<property name="triggers">
            
<list>
                
<ref local ="cron"/>
            
list>
        
property>
    
bean>

beans>
2.服务类

package service;

public class UserService {
    
public void doService(){
        System.out.println(
"User service started!");
    }

}


3.调度类

package schedule;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import service.UserService;

public class TestJob extends QuartzJobBean {

    
private UserService service;
    
    
public UserService getService() {
        
return service;
    }


    
public void setService(UserService service) {
        
this.service = service;
    }


    @Override
    
protected void executeInternal(JobExecutionContext context)
            
throws JobExecutionException {
        
// TODO Auto-generated method stub
        service.doService();
    }


}


4.测试类

package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class QuartzTest {
 
    
public static void main(String[] args) {
        
// TODO Auto-generated method stub
        
        System.out.println(
"Test start!");
        ApplicationContext ctx 
= new ClassPathXmlApplicationContext("xml/JobQuartz1.xml");
       // System.out.println(
"Test end!");
        
    }


}

5.需要加入spring.jar   quartz-all-1.6.0.jar   log4j-1.2.14.jar   commons-collections.jar   jta.jar   commons-logging.jar这几个包

6.log4j.properties内容


# For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.
# For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.
log4j.rootLogger=INFO, stdout, logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=logs\\test.log
log4j.appender.logfile.MaxFileSize=512KB
# Keep three backup files.
log4j.appender.logfile.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n




二、定时执行某方法
1.xml文件 JobQuartz.xml

xml version="1.0" encoding="UTF-8"?>
DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "">

<beans>
    

    
<bean id="job" class="test.TJob">bean>
    
    

    
<bean id="jobtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        
<property name="targetObject">
            
<ref local="job"/>
        
property>
        
<property name="targetMethod">  
            
<value>doAuthvalue>
        
property>
    
bean>
    
    

    
<bean id = "cron" class = "org.springframework.scheduling.quartz.CronTriggerBean">
        
<property name="jobDetail">
            
<ref bean="jobtask"/>
        
property>
        
<property name="cronExpression">
            
<value>0 0 15 * * ?value>
        
property>
    
bean>
    
    

    
<bean autowire = "no" class = "org.springframework.scheduling.quartz.SchedulerFactoryBean">
        
<property name="triggers">
            
<list>
                
<ref local ="cron"/>
            
list>
        
property>
    
bean>

beans>
2.要调度的类

package test;

public class TJob {
    
public void doAuth(){
        System.out.println(
"Task starting...");
    }

}

3.测试类

package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class QuartzTest {
 
    
public static void main(String[] args) {
        
// TODO Auto-generated method stub
        
        System.out.println(
"Test start!");
        ApplicationContext ctx 
= new ClassPathXmlApplicationContext("xml/JobQuartz.xml");
       // System.out.println(
"Test end!");
        
    }


}

三、在web.xml载入applicationContext.xml

  在Spring框架中集成Quartz实现任务调度

  图-1

  b. 配置web.xml

<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="2.5"xmlns=""
  xmlns:xsi=""
  xsi:schemaLocation=" 
    /web-app_2_5.xsd"
>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
  <listener>
    <listener-class>
      org.springframework.web.util.IntrospectorCleanupListener
    </listener-class>
  </listener>
  <listener>
    <listener-class>
      org.springframework.web.context.request.RequestContextListener
    </listener-class>
  </listener>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

c. 配置applicationContext.xml

<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns=""
   xmlns:xsi=""
   xmlns:jee=""
   xsi:schemaLocation="/spring-beans-2.0.xsd
     /spring-jee-2.0.xsd"
>
  <beanid="MyJobDetail"class="org.springframework.scheduling.quartz.JobDetailBean">
    <propertyname="jobClass"value="com.demo.quartz.MyJob"/>
    <propertyname="jobDataAsMap">
      <map>
        <entrykey="size"value="10"></entry>
      </map>
    </property>
    <propertyname="applicationContextJobDataKey"value="applicationContext"/>
  </bean>
  <beanid="MyJobScheduledTask"class="org.springframework.scheduling.quartz.CronTriggerBean">
    <propertyname="jobDetail"ref="MyJobDetail"/>
    <propertyname="cronExpression"value="019106*?*"></property>
  </bean>
  <beanid="HiJobDetail"class="org.springframework.scheduling.quartz.JobDetailBean">
    <propertyname="jobClass"value="com.demo.quartz.HiJob"/>
    <propertyname="jobDataAsMap">
      <map>
        <entrykey="size"value="10"></entry>
      </map>
    </property>
    <propertyname="applicationContextJobDataKey"value="applicationContext"/>
  </bean>
  <beanid="HiJobScheduledTask"class="org.springframework.scheduling.quartz.SimpleTriggerBean">
    <propertyname="startDelay"value="10000"/>
    <propertyname="repeatInterval"value="2000"/>
    <propertyname="jobDetail"ref="HiJobDetail"/>
  </bean>
  <beanid="QuartzJobFactory"class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <propertyname="triggers">
      <list>
        <refbean="MyJobScheduledTask"/>
        <!-- <refbean="HiJobScheduledTask"/>-->
      </list>
    </property>
    <!--设置是否Spring容器初始化后马上启动Scheduler,默认为true。如果设置为false则需要手工启动Scheduler-->
    <propertyname="autoStartup"value="true"/>
  </bean>
</beans>

  d. HiJob类

packagecom.demo.quartz;
importjava.util.Date;
importorg.quartz.Job;
importorg.quartz.JobExecutionContext;
importorg.quartz.JobExecutionException;
publicclassHiJobimplementsJob {
  publicvoidexecute(JobExecutionContextcontext)
      throwsJobExecutionException{
    System.out.println("ThisisHiJob,Runtimeis"+newDate());
  }
}

e. MyJob类

packagecom.demo.quartz;
importjava.util.Date;
importorg.quartz.Job;
importorg.quartz.JobExecutionContext;
importorg.quartz.JobExecutionException;
publicclassMyJobimplementsJob{
  publicvoidexecute(JobExecutionContextcontext)
      throwsJobExecutionException{
    System.out.println("ThisisMyJob,Runtimeis"+newDate());
  }
}

f. Client测试类

packagecom.demo.quartz;
importorg.quartz.Scheduler;
importorg.quartz.SchedulerException;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassClient{
  /**
  *@paramargs
  */

  publicstaticvoidmain(String[]args){
    ApplicationContextcontext= 
      newClassPathXmlApplicationContext("applicationContext.xml");
    Schedulera=(Scheduler)context.getBean("QuartzJobFactory");
    try{
      a.start();
    }catch(SchedulerExceptione){
      e.printStackTrace();
    }
  }
}

在Spring中集成Quartz极大地方便了任务调度功能的实现,并且通过SchedulerFactoryBean能够和Spring容器的生命周期关联,在Spring容器启动时,启动调度器。

阅读(646) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~