您的位置:首页 > 编程语言 > Java开发

Spring的简单定时任务的实现

2016-07-24 21:57 357 查看
搭建最简单的Spring定时任务工程:

1.把Spring通过web.xml注册进来:

<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


2.需要告诉Spring去哪儿扫描组件,在此我使用的是注解的方式,所以要告诉Spring我们是使用注解方式注册任务的,我的配置文件是applicationContext-service.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <!-- 新闻的service -->
<!-- <bean id="newsService" class="com.ssm.service.impl.NewsServiceImpl" /> -->
<context:component-scan base-package="com.ssm.service.*"></context:component-scan>
<context:annotation-config />
<task:annotation-driven/>//使用的注解方式来实现Spring的定时任务

<!-- 开启这个配置,spring才能识别@Scheduled注解     -->
<!-- <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>
<task:scheduler id="qbScheduler" pool-size="10"/>  -->
</beans>


3.注册一个简单的任务,在service下新建一个包task,然后创建一个Spider类,类的的内容表示每逢10秒执行,打印一个语句

package com.ssm.service.task;

import java.util.Date;

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

@Component("spider")
public class Spider {

@Scheduled(fixedRate=10*1000)
public void getNews(){
System.out.println(new Date()+"-------getNews");
}
}


4.运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: