Spring-Task是Spring3.0以后自主开发的定时任务工具,使用起来非常方便,只需要导入spring相关包就可以,支持注解和配置两种方式
下面一起见证它的简单和强大之处
step one 定义任务类
package com.mote.demo;
public class TaskDemo {
public void demo() {
System.out.println("spring-task测试");
}
}
step two 配置文件方式实现定时效果
▶▶ 编写applicationContext-task.xml (开发时,可直接写在applicationContext.xml中)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">
<!-- 配置任务类 -->
<bean id="taskDemo" class="com.mote.demo.TaskDemo"></bean>
<!-- 配置方式一 每30秒执行一次 项目启动时不执行 -->
<task:scheduled-tasks>
<task:scheduled ref="taskDemo" method="demo" cron="0/30 * * * * ?" />
</task:scheduled-tasks>
<!-- 配置方式二 每30秒执行一次 项目启动时调用 -->
<task:scheduled-tasks>
<task:scheduled ref="taskDemo" method="demo" fixed-delay="30000" />
</task:scheduled-tasks>
</beans>
step three @Scheduled注解方式实现
▶▶ 开启@Scheduled注解扫描
<!-- 定义任务类 -->
<bean id="taskDemo" class="com.test.TaskDemo"></bean>
<!-- 开启这个配置,spring才能识别@Scheduled注解 -->
<task:annotation-driven scheduler="qbScheduler" mode="proxy" />
<task:scheduler id="qbScheduler"/>
▶▶定义任务类
import org.springframework.scheduling.annotation.Scheduled;
public class TaskDemo {
@Scheduled(cron="0/30 * * * * ?") //项目启动时不调用,之后每隔30秒执行一次
//@Scheduled(fixedDelay = 30000) //项目启动时调用方法,任务执行完成后,计时30秒再次调用
//@Scheduled(fixedRate = 30000) //项目启动时调用方法,任务开始执行后,计时30秒在此调用
public void demo() {
System.out.println("spring-task测试");
}
}
corn表达式详解
例1:每隔5秒执行一次:*/5 * * * * ?
例2:每隔5分执行一次:0 */5 * * * ?
在26分、29分、33分执行一次:0 26,29,33 * * * ?
例3:每天半夜12点30分执行一次:0 30 0 * * ? (注意日期域为0不是24)
每天凌晨1点执行一次:0 0 1 * * ?
每天上午10:15执行一次: 0 15 10 ? * * 或 0 15 10 * * ? 或 0 15 10 * * ? *
每天中午十二点执行一次:0 0 12 * * ?
每天14点到14:59分,每1分钟执行一次:0 * 14 * * ?
每天14点到14:05分,每1分钟执行一次:0 0-5 14 * * ?
每天14点到14:55分,每5分钟执行一次:0 0/5 14 * * ?
每天14点到14:55分,和18点到18点55分,每5分钟执行一次:0 0/5 14,18 * * ?
每天18点执行一次:0 0 18 * * ?
每天18点、22点执行一次:0 0 18,22 * * ?
每天7点到23点,每整点执行一次:0 0 7-23 * * ?
每个整点执行一次:0 0 0/1 * * ?
例4:每月1号凌晨1点执行一次:0 0 1 1 * ?
每月15号的10点15分执行一次:0 15 10 15 * ?
每月的最后一天的10:15执行一次:0 15 10 L * ?