本文隶属于专题系列: Spring Quartz 定时任务系列

前面已经讲到了spring 3整合Quartz 2来实现时任务,其实从spring 3开始,它本身就已经自带了一套自主开发的定时任务工具Spring-Task,可以将它看成是一个轻量级的Quartz,而且使用起来十分简单,除spring相关的包外不需要额外的包,支持注解和配置文件两种形式。

第一种:配置文件方式

第一步:编写作业类,它是一个普通的Java类,不需要继承和实现任何类和接口:

@Service  
public class TaskJob {  
    public void job1() {  
        System.out.println("任务成功运行。。。");  
    }  
}

第二步:在spring配置文件头中添加spring-task的命名空间及描述:

<beans xmlns="http://www.springframework.org/schema/beans"  
    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">

第三步:spring配置文件中设置具体的任务:

<task:scheduled-tasks>   
        <task:scheduled ref="taskJob" method="job1" cron="0 * * * * ?"/>   
</task:scheduled-tasks>  
<context:component-scan base-package=" com.task " />

说明:ref参数指定的即任务类,method指定的即需要运行的方法,cron及cronExpression表达式,具体写法这里就不介绍了。

<context:component-scan base-package="com.task" />这个配置不消多说了,spring扫描注解用的。

到这里配置就完成了,是不是很简单。

第二种:使用注解形式

从spring 2.5开始,可以方便的使用注解来声明bean,对于定时任务,同样提供了注解@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.即从上一个任务开始到下一个任务开始的间隔,单位是毫秒。

下面我们使用注解来实现一下看看:

第一步:还是编写我们的任务类,和上面基本一样,只不过方法上添加了@Scheduled注解。

@Component("taskJob")  
public class TaskJob {  
    @Scheduled(cron = "0 0 3 * * ?")  
    public void run() {  
        System.out.println("任务成功运行。。。");  
    }  
}

第二步:同样需要在spring配置文件头中添加spring-task的命名空间及描述,另外添加扫描spring-task的配置:

<beans xmlns="http://www.springframework.org/schema/beans"  
    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">
	...
	<!-- 开启这个配置,spring才能识别@Scheduled注解 --> 
	<task:annotation-driven/>
	...
</beans>

配置完毕,我们的任务已经可以运行了。当然你也可以把cron参数换成另外的两个,自己尝试一下吧。spring-task还有很多的参数,这里就不一一解释了,具体可以查看官方的文档。

你可能感兴趣的内容
Spring 之 JMS 监听JMS消息 收藏,4403 浏览
Spring 之 JMS 基于JMS的RPC 收藏,3253 浏览
Spring的BeanFactory和FactoryBean 收藏,10404 浏览
0条评论

selfly

交流QQ群:32261424
Owner