使用场景
比如一个学校,每天都有保洁阿姨定时的去完成某些任务,但是程序员总不可能一直呆在电脑前等着按时按点的去执行某些方法,因此引入了任务调度
使用步骤
第一步,写一个spring配置文件
applicationContext-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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<!--定时任务注解驱动-->
<task:annotation-driven/>
<!-- 扫描到测试类 -->
<context:component-scan base-package="com.offcn"/>
</beans>
写测试类
在包com.offcn下
package com.offcn;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class TaskDemo001 {
//模拟生日发送定时任务
//每秒钟执行一次;6个*是CRON表达式
// * 表示范围内任意值,
// ",":隔开多个值,5,10,15;
// "-":代表范围,0-30执行;
// "/":步长,0/5:每隔五秒执行一次;
// "?":占位符
//第一个*所在的位置代表秒,范围:0-59,
//第二个*所在的位置代表分,范围:0-59
//第三个*所在的位置代表小时,范围:0-23
//第四个*所在的位置代表天,范围:1-31
//第五个*所在的位置代表月,范围:1-12
//第六个*所在的位置代表星期,范围:1-7
//需求1:每天上午10:00执行一次,下午14:00执行一次,晚上18:00执行一次:"0 0 10,14,18 * * *"
//需求2:朝九晚五,每隔半个小时执行一次:"0 0/30 9-17 * * *"
//需求3:每天下午14:00-14:59,每隔一分钟执行一次:"0 0/1 14 * * *"
//需求4:朝九晚五,每隔半个小时执行一次,工作日执行:"0 0/30 9-17 ? * 1-5"
@Scheduled(cron = "0 0/30 9-17 ? * 1-5")
public void sendSms(){
//执行的任务体
System.out.println("生日短信发送定时任务执行中:"+ new Date().toLocaleString());
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
pom.xml略 spring环境所需依赖