Spring Quartz定时任务

文章部分摘自:http://www.cnblogs.com/langke93/archive/2012/11/05/2754958.html

1.如果是web工程,web.xml需要配置监听器:

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

2.applicationContext.xml配置:

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:task="http://www.springframework.org/schema/task"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
            http://www.springframework.org/schema/fex  
            http://www.springframework.org/schema/fex/spring-fex-1.5.xsd  
            http://www.springframework.org/schema/task   
            http://www.springframework.org/schema/task/spring-task-3.0.xsd   
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.1.xsd">
            
     <!-- Enables the Spring Task @Scheduled programming model -->  
     
    <context:component-scan base-package="*" />    
    <task:executor id="executor" pool-size="5" />  
    <task:scheduler id="scheduler" pool-size="10" />  
    <task:annotation-driven executor="executor" scheduler="scheduler" />
</beans>

 

3.加载quartz jar包,配置maven依赖

4.Job类

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Job {

    @Autowired
    BuildService buildService;
 
    /**
     * 定时一小时执行一次
     * */
    @Scheduled(cron="0 0 */1 * * *") 
    public void buildOnTimer(){
        buildService.buildOnTimer();
    }
    
    @Scheduled(cron="*/10 * * * * *") 
    public void s10(){
        System.out.println("10s");
    }
    
    @Scheduled(cron="0 */1 * * * *") 
    public void m1(){
        System.out.println("1m");
    }
    @Scheduled(cron="0 0 */1 * * *") 
    public void h1(){
        System.out.println("1h");
    }
}

 

 cronExpression配置说明

星期的简写:

周一 MON 周二 TUE 周三 WED 周四 THU 周五FRI 周六 SAT 周日 SUN

在MONTH和Day Of Week字段里对字母大小写不敏感

 

Cron表达式范例:

每隔5秒执行一次:*/5 * * * * ?

 每隔1分钟执行一次:0 */1 * * * ?

 每天23点执行一次:0 0 23 * * ?

每天凌晨1点执行一次:0 0 1 * * ?

每月1号凌晨1点执行一次:0 0 1 1 * ?

每月最后一天23点执行一次:0 0 23 L * ?

 每周星期天凌晨1点实行一次:0 0 1 ? * L

在26分、29分、33分执行一次:0 26,29,33 * * * ?

每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?

 

posted @ 2014-10-09 14:46  fenglie  阅读(242)  评论(0)    收藏  举报
版权所有,转载声明