spring-context.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" 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.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.2.xsd"> <bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor" /> <mvc:default-servlet-handler /> <context:component-scan base-package="com.rz.*"></context:component-scan> <!-- 启用注解驱动的定时任务 --> <task:annotation-driven scheduler="myScheduler" /> <!-- 配置线程池,若不配置多任务下会有问题 --> <task:scheduler id="myScheduler" pool-size="10" /> <mvc:annotation-driven /> //... ... //... ... </beans>
定时任务A:
package com.rz.task; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component("aTask") public class ATask { @Scheduled(cron = "0/10 * * * * ? ") // 每10秒执行一次 public void aTask() { System.out.println(""); System.out.println(new Date() + "*********A任务每10秒执行一次进入测试"); } }
定时任务B:
package com.rz.task; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component("bTask") public class BTask { @Scheduled(cron = "0/5 * * * * ? ") // 每5秒执行一次 public void bTask() { System.out.println(new Date() + "*********B任务每5秒执行一次进入测试"); } }定时任务执行时间可依照:http://cron.qqe2.com 进行生成。