spring task 实现定时任务
由于Spring3.0以后自带spring task定时任务工具,使用方法也非常简单,在Spring的架构下不需要额外引入其他jar包,同时还支持注解和配置文件两种形式。
一、注解方式配置(@Scheduled)
1、编写定时任务实体类
@Component public class SpringTaskJob { /* * cron : 秒,分,时,日,月,星期,年(可选) */ @Scheduled(cron = "0/5 * * * * ?") public void job1() { System.out.println(new Date()); System.out.println("每5秒执行一次......"); } }
2、在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:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"> <!-- 注解方式 --> <context:annotation-config /> <context:component-scan base-package="com.dmd.timer" /> <task:annotation-driven/> </beans>
执行效果:
主要是需要在常规的Spring框架配置下添加上如下的配置:
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd"
<!-- 定时任务 -->
<task:annotation-driven />
<!—spring扫描注解的配置 —>
<context:component-scan base-package="com.dmd.timer" />
二、XML的方式配置
1、定时任务实体类
public class SpringTaskJob { public void job1() { System.out.println(new Date()); System.out.println("每5秒执行一次......"); } }
2、配置
<?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:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd">
<!-- 注解方式 -->
<context:annotation-config />
<bean name="testTask" class="com.dmd.timer.SpringTaskJob"
lazy-init="false"></bean>
<task:scheduled-tasks>
<!-- cron : 秒,分,时,日,月,星期,年(可选) -->
<task:scheduled ref="testTask" method="job1" cron="0/5 * * * * ?" />
</task:scheduled-tasks>
</beans>