Quartz 注解实现定时任务

quartz定时任务的实现在Spring中使用的注解名称为:@Scheduled
可以作用于方法和类上

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {
    String cron() default "";
    String zone() default "";
    long fixedDelay() default -1;
    String fixedDelayString() default "";
    long fixedRate() default -1;
    String fixedRateString() default "";
    long initialDelay() default -1;
    String initialDelayString() default "";

}

我们主要用的就是第一个参数,cron,配置定时任务运行的周期。
我们来通过@Scheduled来实现我们的第一个注解配置的定时任务

package com.wangcc.quartz;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @ClassName: HelloJob
 * @Description: http://blog.csdn.net/tanyongbing1988/article/details/45689987
 * @author wangcc
 * @date 2017年10月23日 下午3:26:57
 * 
 */
@Service

public class HelloJob {

    public HelloJob() {
        System.out.println("HelloJob创建成功");
    }

     @Scheduled(cron = "0/1 * * * * ? ") // 每隔1秒隔行一次
    public void run() {
        System.out.println("Hello MyJob  " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date()));
    }


}

要想@Scheduled注解发挥作用,我们还需要在配置文件中加上一些东西。
1.在Spring配置文件中添加 配置

我们知道在spring中要想类中使用的注解被Spring容器检测到,要在配置文件中指定对应的报名,使用

<context:component-scan base-package="com.wangcc.ssm,com.wangcc.quartz,com.wangcc.test.properties" />  

而我们要使得Spring quartz定时任务的相应注解生效,也需要在Spring配置文件中加一句话。

             <task:annotation-driven/>    

这个annotation-driven是不是很熟悉,我们在配置springmvc的时候也应用到了相似的配置。

<mvc:annotation-driven/>

是告知Spring,我们启用注解驱动。然后Spring会自动为我们注册springmvc开发相关的Bean到工厂中,来处理我们的请求。这个在我们分析SpringMVC源码的时候会细说。
同理<> 也是告知Spring,我们的quartz定时任务使用注解驱动的,会自动去找使用了@Scheduled的注解方法,完成定时任务的处理。

2.在Spring配置文件中为task增加相应的命名空间。
xmlns:末尾加上

xmlns:task="http://www.springframework.org/schema/task" 

xsi:schemaLocation加上

http://www.springframework.org/schema/task    
http://www.springframework.org/schema/task/spring-task-3.0.xsd 

然后,我们可以开始编写测试类来测一下程序是否成功执行了。

package com.wangcc.test.quartz;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class) // 表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = { "classpath:mybatis-spring.xml" })
public class TestQuartz {
    @Test
    public void testquartz() throws InterruptedException {
        Thread.sleep(100000L);

        System.out.println("Test quartz");
    }

}

这里为了测试到效果,需要使用 Thread.sleep(100000L);
让测试方法执行的线程休眠一下,要不然这个测试类的执行只会初始化SpringBean注册等工作,然后直接执行测试方法, 无法测试定时任务了。
为了让运行周期的配置更加灵活,我们在实际项目中打算使用配置文件来配置cron的value,那我们应该怎么做呢。
这里我们就需要使用一个新接触的注解:@PropertySource

这个注解只能作用在类上

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {
    String name() default "";
    String[] value();
    boolean ignoreResourceNotFound() default false;

}

使用这个注解,我们就可以将配置文件中的东西直接在Java代码中读取了。

在使用时,我们一般需要指定value,value指向文件所在路径,如下

package com.wangcc.quartz;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @ClassName: HelloJob
 * @Description: 
 * @author wangcc
 * @date 2017年10月23日 下午3:26:57
 * 
 */
@Service
@PropertySource(value = "classpath:batch.properties")

public class HelloJob {

    public HelloJob() {
        System.out.println("HelloJob创建成功");
    }

    // @Scheduled(cron = "0/1 * * * * ? ")
    @Scheduled(cron = "${helloBatch}") // 每隔1秒隔行一次
    public void run() {
        System.out.println("Hello MyJob  " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date()));
    }

当我们这样配置后重新执行测试类,我们发现报错了,报错信息提示:Could not resolve placeholder ‘batch.properties’ in string value “${helloBatch}

一开始看到这样的报错信息我是蒙蔽的,心想是不是这个@PropertySource注解不好使呀,还是我这个注解配的有问题呀,上网查找原因后发现,原来是这样的。

在spring的xml配置文件中当有多个*.properties文件需要加载时。我们需要进行一些特殊的配置,

加上

               <property name="ignoreUnresolvablePlaceholders" value="true" /> 

使得配置文件配置节点如下:

  <bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="location" value="classpath:jdbc.properties" />  
               <property name="ignoreUnresolvablePlaceholders" value="true" /> 
    </bean>  

原因如下:

Spring容器采用反射扫描的发现机制,在探测到Spring容器中有一个org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的Bean就会停止对剩余PropertyPlaceholderConfigurer的扫描(Spring 3.1已经使用PropertySourcesPlaceholderConfigurer替代PropertyPlaceholderConfigurer了)。

而这个基于命名空间的配置,其实内部就是创建一个PropertyPlaceholderConfigurer Bean而已。换句话说,即Spring容器仅允许最多定义一个PropertyPlaceholderConfigurer(或),其余的会被Spring忽略掉(其实Spring如果提供一个警告就好了)。 然后我们使用注解,相当于又创建一个PropertyPlaceholderConfigurer Bean,就造成了有多个Bean就会有问题。

加上这个配置后,我又跑了一遍,信心满满的认为这次总稳了吧,然而并没有,还是报错,我的天,报错信息大意为cron需要指定6或7个域,而我只提供了一个域,刚开始很纳闷为啥会报这个错呀,明明我就是配的6个域呀,怎么会错呢,这不科学呀。这肯定还是读文件的时候出问题了,上网查找,发现果然是这样,仅仅上面的配置可以读取配置文件,但是是无法正确的读取配置文件的内容的,如果想要正确的读取,需要配置

@Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }

否则会造成没法正确读取中配置文件中的值。

更改后的类为:

package com.wangcc.quartz;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @ClassName: HelloJob
 * @Description: 
 * @author wangcc
 * @date 2017年10月23日 下午3:26:57
 * 
 */
@Service
@PropertySource(value = "classpath:quartz.properties")

public class HelloJob {

    public HelloJob() {
        System.out.println("HelloJob创建成功");
    }

    // @Scheduled(cron = "0/1 * * * * ? ")
    @Scheduled(cron = "${helloBatch}") // 每隔1秒隔行一次
    public void run() {
        System.out.println("Hello MyJob  " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date()));
    }

    /*
     * 
     * 要注意的是,要使用
     * 
     * @Bean public static PropertySourcesPlaceholderConfigurer
     * propertyConfigInDev() { return new PropertySourcesPlaceholderConfigurer(); }
     * 
     * 才能让spring正确解析出${} 中的值 http://blog.csdn.net/itchiang/article/details/51144218
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

batch.proerties

helloBatch=0/1 * * * * ?

转载,原作者BryantLmm

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 193,812评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,626评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,144评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,052评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,925评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,035评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,461评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,150评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,413评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,501评论 2 307
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,277评论 1 325
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,159评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,528评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,868评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,143评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,407评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,615评论 2 335

推荐阅读更多精彩内容