1、写好JAVA类TimerTaskTest 必须继承TimerTask 

package spring;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.Date;

import java.util.TimerTask;

import org.springframework.beans.BeansException;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TimerTaskTest extends TimerTask {

public static void main(String[] args) throws IOException {

try {

try {

new ClassPathXmlApplicationContext(new String[] {"beans-config.xml"});

} catch (BeansException e) {

e.printStackTrace();

}

} catch (Exception e) {

e.printStackTrace();

}

System.out.println("启动 Task..");

System.out.println("请输入 exit 关闭 Task: ");

BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));

while(true) {

if(reader.readLine().equals("exit")) { System.exit(0);}

}

}


@Override

public void run() {

System.out.println(new Date().toLocaleString()+">>>>>>>>>>正在执行定时任务");

}

}

2、配置Spring 的 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:context="http://www.springframework.org/schema/context" 

    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 ">  

    

    

<bean id="demoTask" class="spring.TimerTaskTest"/>

<bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">

<property name="timerTask">

<ref bean="demoTask"/>

</property>

<property name="period">

<value>60000</value>

</property>

<property name="delay">

<value>10000</value>

</property>

</bean>

<bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean">

<property name="scheduledTimerTasks">

<list>

<ref bean="scheduledTimerTask"/>

</list>

</property>

</bean>

</beans>



3、在上面写的JAVA类中的main方法里面,运行即可执行定时任务


备注:项目需要一些jar包,欢迎联系我的扣扣(1051479609)问我要。
Spring ScheduledTimerTask 定时任务执行_Spring ScheduledTime