spring 4.1.7
jdk1.8
1.时间设置在javaBean的@注解里
spring-task.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd"
default-lazy-init="false">
<!-- 定时器开关 -->
<task:annotation-driven />
<!-- 扫描mytask包下的文件 -->
<context:component-scan base-package="com.test.mytask" />
</beans>
javaBean:
package com.test.mytask;
import java.util.List;
@Component("test")
public class Test{
@Scheduled(cron = "*/5 * * * * ?")
public void testMethod(){
System.out.println("每5秒显示一次,"+new Date());
}
}
--------------------------------------------------------------------------
2.时间设置在spring-task.xml里
spring-task:
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd"
default-lazy-init="false">
<!-- 此处和另一个方法用到注解不一样,不必有driver-->
<context:annotation-config />
<!-- 扫描mytask包下的文件 -->
<context:component-scan base-package="com.test.mytask" />
<bean id="Test" class="com.test.mytask.Test" />
<task:scheduled-tasks>
<task:scheduled ref="Test" method="testMethos" cron="*/5 * * * * ?" />
</task:scheduled-tasks>
</beans>
javaBean:
package com.test.mytask;
import java.util.Date;
@Component("Test")
public class Test{
@Scheduled
public void testMethod(){
System.out.println("每5秒显示一次,"+new Date());
}
}
比较:
在@scheduled注解中写时间设置,不用太多的配置xml ;
但是在xml配置文件中写时间设置方便别人修改和管理,建议采用xml中设置时间的方法