Schedule存在spring-context.jar包中。

实现简单步骤:

1、配置bean.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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd ">

<!-- 开启定时任务 -->
<task:annotation-driven />

<context:component-scan base-package="com.jsoft.testspring" />

<context:annotation-config />

<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

</beans>


代码实现:



package com.jsoft.testspring.testmvchelloworld;

import java.text.SimpleDateFormat;
import java.util.Date;

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

@Component
public class ScheduleTest {

@Scheduled(cron = "0/5 * * * * ?")
public void schTest1() {
Date date = new Date();
SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sim.format(date);
System.out.println("这是spring定时器1,每五秒执行一次,当前时间:" + dateStr);
}
}


注意要加@Component这类的注解。

示例工程:​​https://github.com/easonjim/5_java_example/tree/master/springtest/test24/testmvchelloworld​