继承:http://www.cnblogs.com/crazylqy/p/4220743.html
spring设置容器启动时运行线程类(可循环执行)
修改以下两文件,
1.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: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="messagePrinterTask" class="MessagePrinterTask">
</bean> <!-- 这样设置容器一启动就自动运行某个线程 start -->
<bean id="springScheduleExecutorTask" class="org.springframework.scheduling.concurrent.ScheduledExecutorTask">
<property name="runnable" ref="messagePrinterTask" /><!-- messagePrinterTask为线程类 -->
<!-- 容器加载10秒后开始执行 -->
<property name="delay" value="10000" />
<!-- 每次任务间隔 5秒,循环执行该线程,删除该设定就容器启动后只执行一次-->
<property name="period" value="5000" />
</bean> <bean id="springScheduledExecutorFactoryBean" class="org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean">
<property name="scheduledExecutorTasks">
<list>
<ref bean="springScheduleExecutorTask" />
</list>
</property>
</bean>
<!-- 这样设置容器一启动就自动运行某个线程 end --> </beans>
测试运行
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
}
}
结果
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAARUAAACFCAIAAAD6nftCAAACOElEQVR4nO3b200CYRhF0b+uKWjqmRKoYpqhielgfEAQb6g7GBNcKz4g8YHE7ODlO2Pbtm3bDofD6cHOHa3zPubLJ/sY+/qXL4dvW6++cbcM/fym4z6NfZw/luNfvx6+ST/w+/QDnX6gu0M/6zxO5vWLJ+HB3Ov957hM71P58El4HPqB7rN+1nnMyzKdfgabnv/wus6XHN6moR/+oxv9nH93WeerR/qBF7fef96loh94RT/Q/bSf069Cx2V686dp/fAf/aif527GGNOynL/g8tz1P3w+fBIejfsD6PQDnX6g0w90+oFOP9DZL0Dn/ho6/UBnvwCd/QJ07q+h0w909gvQ2S9A5/4AOv1Apx/o9AOdfqDTD3T2C9C5v4ZOP9DZL0BnvwCd+2vo9AOd/QJ09gvQuT+ATj/Q6Qc6/UCnH+j0A539AnTur6HTD3T2C9DZL0Dn/ho6/UBnvwCd/QJ07g+g0w90+oFOP9DpBzr9QGe/AJ37a+j0A539AnT2C9C5v4ZOP9DZL0BnvwCd+wPo9AOdfqDTD3T6gU4/0NkvQOf+Gjr9QGe/AJ39AnTur6HTD3T2C9DZL0Dn/gA6/UCnH+j0A51+oNMPdPYL0Lm/hk4/0NkvQGe/AJ37a+j0A539AnT2C9C5P4BOP9DpBzr9QKcf6PQDnf0CdO6vodMPdPYL0NkvQOf+Gjr9QGe/AJ39AnTuD6DTD3T6gU4/0OkHOv1Apx/o9AOdfqDTD3T6gU4/0OkHOv1A9wS9Dnwh7o5u9gAAAABJRU5ErkJggg==" alt="" />