使用xml的方式,会配置很多bean的信息,如果使用注解的方式,会更方便运用,配置注解相对简单
注解配置
spring配置文件里增加命令空间:
xmlns:task="http://www.springframework.org/schema/task" http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
配置spring扫描和task扫描
<task:annotation-driven/>
参考代码
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" 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-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"> <!-- 扫描组件 --> <context:annotation-config/> <context:component-scan base-package="com.anson.*"/> <!-- 定时任务扫描 --> <task:annotation-driven/> </beans>
然后配置一段带有注解的Java类即可
package com.anson.annotation;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class HelloJob {
@Scheduled(cron = "*/5 * * * * ?") //每隔5秒执行一次
public void test() throws Exception {
System.out.println("Hello Annotation Job......");
}
}以上配置就算完成了,在项目启动时,会进行spring实例化并执行定时任务。
Schedued类介绍
Scheduled类源码如下
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.scheduling.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@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 -1L;
String fixedDelayString() default "";
long fixedRate() default -1L;
String fixedRateString() default "";
long initialDelay() default -1L;
String initialDelayString() default "";
}Scheduled类的可配置属性项:
String | cron一个类似cron的表达 |
long | fixedDelay在最后一次调用结束和下一次调用开始之间的固定时间段执行注释方法。 |
String | fixedDelayString在最后一次调用结束和下一次调用开始之间的固定时间段执行注释方法。 |
long | fixedRate在调用之间以固定的时间段执行带注释的方法。 |
String | fixedRateString在调用之间以固定的时间段执行带注释的方法。 |
long | initialDelay在首次执行fixedRate()或fixedDelay()任务之前要延迟的毫秒数。 |
String | initialDelayString在首次执行fixedRate()或fixedDelay()任务之前要延迟的毫秒数。 |
String | zonecron表达式将被解析的时区。 |
未经允许请勿转载:程序喵 » Quartz 定时任务使用 —— 集成Spring使用注解配置(五)
程序喵