一个简单的Spring定时任务的 demo,全部代码见下载地址:https://download.csdn.net/download/yx0628/10511753
对于 applicationContext 的配置如下:调度器线程池 task:scheduler 和 task:executor 的意义在后边例子中会详细的测试和说明。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.1.xsd"
xmlns:task="http://www.springframework.org/schema/task">
<context:annotation-config />
<task:annotation-driven scheduler="myScheduler" executor="myExecutor"/>
<!-- 调度线程池配置 -->
<task:scheduler id="myScheduler" pool-size="5"/>
<!-- 执行线程池配置 -->
<task:executor id="myExecutor" pool-size="5"/>
<context:component-scan base-package="com.zaimeibian" />
</beans>a
package com.zaimeibian.task;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class PrintTask {
DateFormat df = new SimpleDateFormat("HH:mm:ss");
// 这个Async注解,代表当前任务是要异步执行的
@Async
@Scheduled(fixedRate = 5000)
public void printA(){
System.out.println("A执行 " + df.format(new Date()));
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
System