loushang 2016(基于spring3.2)的定时任务配置---spring task

一直对定时任务充满好奇,但一直没有对其进行深入研究,趁项目空暇时间稍微研究下定时任务的使用,因项目基于spring3.2完全支持spring task定时任务,为方便起见,就是用spring task来进行定时任务设置,目前有两种实现方法,一种是通过注解(@Scheduled)实现,另一种是直接在xml文件里配置但无论哪一种方式都得在扫描的xml配置。

首先看下路径:
早配置扫描时进行配置定时任务,如下:


springtask.xml的配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd
">
<!-- 注解的开关 -->
<context:annotation-config />
<!-- 注释资源扫描包路径 -->
<context:component-scan base-package="dsrw.test" />
<!-- xml配置类的定时执行 -->
<task:annotation-driven />
<!-- 此处的id也可以使用在class里面使用@Component("myTaskXml")实现-->
<bean id="myTaskXml" class="dsrw.test.taskxml"></bean>

<--通过配置xml实现定时执行, 这里表示的是每隔五秒执行一次 -->
<!-- 
<task:scheduled-tasks> 
<task:scheduled ref="myTaskXml" method="方法名" cron="*/5 * * * * ?" />
<task:scheduled ref="myTaskXml" method="job3" cron="*/10 * * * * ?"/>
</task:scheduled-tasks>
--> 
</beans> 



附dsrwtestimp.java的代码---《注解方式》
package dsrw.test;

import java.text.SimpleDateFormat;
import java.util.Locale;

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

@Service
public class dsrwtestimp implements Idsrwtest {
@Scheduled(cron="0/5 * * * * ? ")
public void job1() {
String time = new SimpleDateFormat("MMM d,yyyy KK:mm:ss a",Locale.ENGLISH).format(System.currentTimeMillis());
System.out.println("任务进行1:"+time);
}
}


myTaskXml.java的代码如下----《xml里面配置方法》
package dsrw.test;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component("myTaskXml")
public class taskxml {
public void job2() {
System.out.println("任务进行2中。。。");
}
@Scheduled(cron="0/5 * * * * ? ")
public void job3() {
String time = new SimpleDateFormat("MMM d,yyyy KK:mm:ss a",Locale.ENGLISH).format(System.currentTimeMillis());
System.out.println("任务进行3:"+time);
}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值