spring自带的定时任务功能,基于注解和xml配置
基于注解和xml的配置,可以分离出来单独使用。
1、spring的配置文件
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns:p="http://www.springframework.org/schema/p" 4 xmlns:task="http://www.springframework.org/schema/task" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:aop="http://www.springframework.org/schema/aop" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 10 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd 11 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 12 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 13 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"> 14 15 <task:annotation-driven /> <!-- 定时器开关--> 16 17 <bean id="myTaskXml" class="com.spring.task.MyTaskXml"></bean> 18 19 <task:scheduled-tasks> 20 <!-- 21 这里表示的是每隔五秒执行一次 22 --> 23 <task:scheduled ref="myTaskXml" method="show" cron="*/5 * * * * ?" /> 24 <task:scheduled ref="myTaskXml" method="print" cron="*/10 * * * * ?"/> 25 </task:scheduled-tasks> 26 27 <!-- 自动扫描的包名 --> 28 <context:component-scan base-package="com.spring.task" /> 29 30 </beans>
2、基于xml的定时任务
1 package com.spring.task; 2 3 /** 4 * 基于xml的定时器 5 * @author hj 6 */ 7 public class MyTaskXml { 8 9 10 public void show(){ 11 System.out.println("XMl:is show run"); 12 } 13 14 public void print(){ 15 System.out.println("XMl:print run"); 16 } 17 }
3、基于注解的定时器任务
1 package com.spring.task; 2 3 import org.springframework.scheduling.annotation.Scheduled; 4 import org.springframework.stereotype.Component; 5 6 /** 7 * 基于注解的定时器 8 * @author hj 9 */ 10 @Component 11 public class MyTaskAnnotation { 12 13 /** 14 * 定时计算。每天凌晨 01:00 执行一次 15 */ 16 @Scheduled(cron = "0 0 1 * * *") 17 public void show(){ 18 System.out.println("Annotation:is show run"); 19 } 20 21 /** 22 * 心跳更新。启动时执行一次,之后每隔2秒执行一次 23 */ 24 @Scheduled(fixedRate = 1000*2) 25 public void print(){ 26 System.out.println("Annotation:print run"); 27 } 28 }
4、测试
1 package com.spring.test; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 7 public class Main { 8 public static void main(String[] args) { 9 ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-mvc.xml"); 10 } 11 }