Spring定时任务的实现方式--Spring Task

本文介绍Spring3.0以后自主开发的定时任务工具,spring task,可以将它比作一个轻量级的Quartz,而且使用起来很简单,除spring相关的包外不需要额外的包,而且支持注解和配置文件两种。

方式一:使用配置文件

1.编写作业类,不需要继承任何类或实现任何接口

package com.Solin.Timer;

import java.util.Date;

public class SpringTimerTest {
	public void say() {  
        System.out.println("这个真好用!!!" + new Date());  
    }  
  
    public void hello(){  
        System.out.println("hello!!!");  
    }  
}

2.在spring配置文件头中添加命名空间及描述

<beans xmlns="http://www.springframework.org/schema/beans" 
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd ">

3.spring配置文件中设置具体的任务

<!--  注册bean  -->
	<bean id="springTimerTest" class="com.Solin.Timer.SpringTimerTest"></bean>
  	<!--  开启任务调度  -->
    <task:scheduled-tasks>  
        <!-- 这里表示的是从第五秒开始 ,每三秒执行一次 (而不是 三分之五 秒执行一次哦~~)    -->
        <task:scheduled ref="springTimerTest" method="say" cron="5/3 * * * * ?" />  
        <task:scheduled ref="springTimerTest" method="hello" cron="5/3 * * * * ?"/>  
    </task:scheduled-tasks>

说明:ref参数指定的即任务类,method指定的即需要运行的方法,cron是表达式,表示在什么时候进行任务调度。


4.启动项目,输出信息:

这个真好用!!!Fri Nov 04 14:45:59 CST 2016
hello!!!
hello!!!
这个真好用!!!Fri Nov 04 14:46:05 CST 2016
hello!!!
这个真好用!!!Fri Nov 04 14:46:08 CST 2016


方式二:使用注解形式

1.编写作业类,不需要继承任何类或实现任何接口

package com.Solin.Timer;

import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class SpringTimerTest {
	@Scheduled(cron="0/5 * * * * ? ") //每5秒执行一次
	public void myTest(){
		System.out.println("进入测试  " + new Date());
	}
}

2.在spring配置文件头中添加命名空间及描述

<beans xmlns="http://www.springframework.org/schema/beans" 
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd ">

3.spring配置文件具体配置

<!-- 组件扫描 -->
<context:component-scan base-package="com.Solin.Timer" />
<!-- 定时器开关-->
<task:annotation-driven /> 
配置完毕,当然spring task还有很多参数,我就不一一解释了,具体参考xsd文档:http://www.springframework.org/schema/task/spring-task-3.2.xsd


4.启动项目,输出信息:

进入测试  Fri Nov 04 15:09:30 CST 2016
进入测试  Fri Nov 04 15:09:35 CST 2016
进入测试  Fri Nov 04 15:09:40 CST 2016
进入测试  Fri Nov 04 15:09:45 CST 2016
进入测试  Fri Nov 04 15:09:50 CST 2016


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值