Spring定时器简单应用实现,如下:
首先、Spring配置文件:
<?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:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd "> <description>spring-configuration</description> <bean id="timerTask" class="com.charles.spring.service.impl.TimerTaskImpl"></bean> <task:scheduled-tasks> <task:scheduled ref="timerTask" method="doTimerTask" cron="0/5 * * * * ?" /> </task:scheduled-tasks> </beans>
其次、相关定时器接口(忽略不计,只是定义一个方法)、类:
package com.charles.spring.service.impl; import com.charles.spring.service.TimerTask; public class TimerTaskImpl implements TimerTask { @Override public void doTimerTask() throws Exception { System.out.println("Hello Timer"); } }
最后测试,测试项目是Java项目,所以只需要加载Spring就可以了,如下:
package com.charles.spring.handler; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Timer { public static void main(String[] args) { @SuppressWarnings({ "unused", "resource" }) ApplicationContext context = new ClassPathXmlApplicationContext("config/spring-config.xml"); try { Thread.sleep(10*60*1000); } catch (Exception e) { } } }
结束。结果: