一、说明
Spring 3.0以后自带的Spring Task,是一个轻量级的定时任务工具,而且使用起来很简单,除spring相关的包外不需要额外的包,支持注解和配置文件两种形式
二、使用
1、配置方式
1)创建Job作业
package com.xl.task;
import org.springframework.stereotype.Component;
@Component
public class SimpleCfgJob {
public void doJob() throws Exception {
System.out.println("Job start...");
}
}
2)配置Cfg文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" 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">
<!-- 任务列表 -->
<task:scheduled-tasks>
<!-- 时间间隔的属性配置,三必选一:-->
<!-- fixed-delay: 上一个任务完成到下一个任务开始的间隔(毫秒); fixed-rate: 上一个任务开始到下一个任务开始的间隔(毫秒); cron: Cron表达式(秒 分 时 日 月 周几 [年]) -->
<task:scheduled ref="simpleCfgJob" method="doJob" fixed-rate="5000"/>
</task:scheduled-tasks>
<!-- 注解扫描 -->
<context:component-scan base-package="com.xl.task" />
</beans>
2、注解方式1)创建Job作业
package com.xl.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class SimpleAnnJob {
@Scheduled(fixedRate = 5000) //注解任务属性
public void doJob() throws Exception {
System.out.println("Job start...");
}
}
2)配置Cfg文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" 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">
<!-- Spring扫描注解的配置 -->
<context:component-scan base-package="com.xl.task" />
<!-- 开启这个配置, Spring才能识别@Scheduled注解 -->
<task:annotation-driven />
</beans>