Spring任务调度之Spring-Task
⼀.前⾔
上⾯两篇介绍了在Spring 中使⽤与Quartz,本篇将介绍Spring3.0以后⾃主开发的定时任务⼯具,spring task,可以将它⽐作⼀个轻量级的Quartz,⽽且使⽤起来很简单,除spring相关的包外不需要额外的包,⽽且⽀持注解和配置⽂件两种形式,下⾯将分别介绍这两种⽅式。⼆、第⼀种:配置⽂件⽅式
第⼀步:编写作业类
即普通的pojo,如下:
import org.springframework.stereotype.Service;
@Service
public class TaskJob {
public void job1() {
System.out.println(“任务进⾏中。。。”);
}
}
第⼆步:spring配置
<task:scheduled-tasks>
<task:scheduled ref="taskJob" method="job1" cron="0 * * * * ?"/>
</task:scheduled-tasks>
<context:component-scan base-package=" ask " />
</beans>
说明:ref参数指定的即任务类,method指定的即需要运⾏的⽅法,cron及cronExpression表达式。<context:component-scan base-package="ask" />这个配置不消多说了,spring扫描注解⽤的。
第⼆种:使⽤注解形式
也许我们不想每写⼀个任务类还要在xml⽂件中配置下,我们可以使⽤注解@Scheduled,我们看看源⽂件中该注解的定义:
@Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scheduled
{
public abstract String cron();
public abstract long fixedDelay();
public abstract long fixedRate();
}
可以看出该注解有三个⽅法或者叫参数,分别表⽰的意思是:
cron:指定cron表达式。
fixedDelay:官⽅⽂档解释:An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds.即表⽰从上⼀个任务完成开始到下⼀个任务开始的间隔,单位是毫秒。
fixedRate:官⽅⽂档解释:An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds.即从上⼀个任务开始到下⼀个任务开始的间隔,单位是毫秒。
第⼀步:编写pojo
import org.springframework.stereotype.Component;
@Component(“taskJob”)
public class TaskJob {
@Scheduled(cron = "0 0 3 * * ?")
public void job1() {
System.out.println(“任务进⾏中。。。”);
}
}
第⼆步:添加task相关的配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
xmlns:xsi="/2001/XMLSchema-instance" xmlns:aop="/schema/aop"      xmlns:context="/schema/context"
spring framework版本
xmlns:tx="/schema/tx"
xmlns:task="/schema/task"
xsi:schemaLocation="
/schema/beans /schema/beans/spring-beans-3.0.xsd          /schema/aop /schema/aop/spring-aop-3.0.xsd
/schema/context
/schema/jdbc/spring-jdbc-3.0.xsd
/schema/tx /schema/tx/spring-tx-3.0.xsd
/schema/task /schema/task/spring-task-3.0.xsd"
default-lazy-init="false">
<context:annotation-config />
<!—spring扫描注解的配置  —>
<context:component-scan base-package="ask" />
<!—开启这个配置,spring才能识别@Scheduled注解  —>
<task:annotation-driven scheduler="qbScheduler" mode="proxy"/>
<task:scheduler id="qbScheduler" pool-size="10"/>
说明:理论上只需要加上<task:annotation-driven />这句配置就可以了,这些参数都不是必须的。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。