使用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扫描
参考代码<?xml version="1.0" encoding="UTF-8"?>
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">
然后配置一段带有注解的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类的可配置属性项:Stringcron
一个类似cron的表达
longfixedDelay
在最后一次调用结束和下一次调用开始之间的固定时间段执行注释方法。
StringfixedDelayString
在最后一次调用结束和下一次调用开始之间的固定时间段执行注释方法。
longfixedRate
在调用之间以固定的时间段执行带注释的方法。
StringfixedRateString
在调用之间以固定的时间段执行带注释的方法。
longinitialDelay
在首次执行fixedRate()或fixedDelay()任务之前要延迟的毫秒数。
StringinitialDelayString
在首次执行fixedRate()或fixedDelay()任务之前要延迟的毫秒数。
Stringzone
cron表达式将被解析的时区。