spring Quartz基于配置文件和注解的实现

2014-11-23 21:35:47 · 作者: · 浏览: 11

这里只是做简单的记录如何实现。

一、基于配置文件的实现

①编写需要调度的类

package com.study;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
//@Component
public class QuartzJob {
	public QuartzJob(){
		System.out.println("Quartzjob创建成功");
	}
	//@Scheduled(cron = "0/1 * *  * *   ")
	public void run(){
		System.out.println("Quartz执行的任务调度");
	}
}

注:里面的注解是后面的是注解的实现中用到的

②设置配置文件spring-quartz.xml

  



  
	
   
	
   
	
    
     
     
      
     
     
     
     
      run
      
     
   
	
   
	
    
     
      
     
     
     
      
     
      0/1 * * * *  
      
     
   
	
   
	
    
     
      
       
      
     
   


  
注意cron表达式,这里配置的是每隔1s执行。

③启动spring容器

package com.study;

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

public class Test {
	public static void main(String[] args) {
		System.out.println("启动spring容器");
		ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring-quartz.xml");
	}
}

二、基于注解的实现

①配置需要调度的类,并添加注解

package com.study;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class QuartzJob {
	public QuartzJob(){
		System.out.println("Quartzjob创建成功");
	}
	@Scheduled(cron = "0/1 * *  * *   ")
	public void run(){
		System.out.println("Quartz执行的任务调度");
	}
}

②添加配置文件

  

  
    
     
    
   
    
   

  
	

③启动容器,这里通过配置web.xml启动

  

  
	
    
    
     contextConfigLocation
     
    
     classpath:spring-quartz2.xml
     
   
	
    
    
     org.springframework.web.context.ContextLoaderListener
     
   
  
    
    
     index.
     jsp
     
   

  

这里不知道为何采用ClassPathXMLApplicationContext启动时,报错。看两种方式的配置文件不同,估计是解析xml文件的方式不同。(dom/sax)