SpringMVC添加定时器

本文介绍了如何在SpringMVC项目中添加定时器,详细讲述了所需的文件结构、依赖jar包,以及配置springMVC-servlet.xml和编写VendorTask.java的具体步骤。通过设置cron表达式,实现了服务器启动后每5秒执行一次的任务。此记录旨在备查。
摘要由CSDN通过智能技术生成

本章讲解springMVC中实现定时器,此时基于上一章eclipse搭建springmvc项目框架

文件结构


定时器所需jar

aopalliance-1.0.jar

步骤

1、springMVC-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 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.0.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd  
    http://www.springframework.org/schema/mvc  
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
    http://www.springframework.org/schema/task   
    http://www.springframework.org/schema/task/spring-task-3.0.xsd">
	<!-- 默认扫描的包路径 -->
	<context:component-scan base-package="*" />

	<!-- 添加注解驱动 -->
	<mvc:annotation-driven />

	<!-- 定义跳转的文件的前后缀 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<task:executor id="executor" pool-size="5" />
	<task:scheduler id="schedule" pool-size="10" />
	<task:annotation-driven executor="executor"
	scheduler="schedule" />

</beans>

注:添加了task

2、VendorTask.java

package net.csdn.blog.springmvc.timer;

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

@Component
public class VendorTask {

	// private static Logger log = Logger.getLogger(VendorTask.class);

	@Scheduled(fixedDelay = 5000)
	public void doSomethingWithDelay() {
		System.out.println("I'm doing with delay now!");
	}

	@Scheduled(fixedRate = 5000)
	public void doSomethingWithRate() {
		System.out.println("I'm doing with rate now!");
	}

	@Scheduled(cron = "0/5 * * ? * *")
	public void doSomethingWithCron() {
		System.out.println("I'm doing with cron now!");
	}

}

注:cron效果为服务器启动之后每过5s钟执行一次,具体的写法可参考Spring定时器配置方式

3、效果


此文仅为记录从无到有的过程,以备以后查看。

未完待续...


注:转载请注明来源。


参考文章:Spring定时器配置文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值