第一步
创建一个maven工程,打包方式为war
第二步
在web.xml中加载spring容器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--加载spring容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-jobs.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
创建spring-jobs.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/task http://www.springframework.org/schema/task/spring-task.xsd
">
<!--将定时任务类交给Spring容器管理-->
<bean id="task" class="com.trc.jobs.TaskDemo"></bean>
<task:scheduled-tasks>
<!--ref:要使用的定时任务类
method:你想要定时执行的方法
initial-delay:容器创建后多少毫秒后执行这个方法
fixed-delay:容器创建后每隔多少毫秒执行一次-->
<!--第一种方式-->
<task:scheduled ref="task" method="hello" initial-delay="1000" fixed-delay="3000"/>
<!--第二种方式-->
<!--<task:scheduled ref="task" method="hello" cron="0 0 2 L * ?"/>-->
</task:scheduled-tasks>
<!-- <task:annotation-driven/>
<context:component-scan base-package="com.trc.jobs"/>-->
</beans>
创建定时任务类
package com.trc.jobs;
/**
* 定时任务类
*/
public class TaskDemo {
public void hello() {
System.out.println("123~~~");
//这里就编写具体的业务操作
}
}
第三步、测试
package com.trc.jobs;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by Tangcancan on 2019/12/17 18:20
*/
public class Test {
public static void main(String[] args) {
new ClassPathXmlApplicationContext("spring-jobs.xml");
}
}
最后,可将它修改为注解方式
将spring-jobs.xml中的配置改为
<task:annotation-driven/>
<context:component-scan base-package="com.trc.jobs"/>
就是上面注释的地方
然后在定时任务类里
类上加上 @Component
方法上加上 @Scheduled(cron = “0 0 2 * * ?”)
然后就是cron表达式的学习~
cron表达式分为七个域,之间使用空格分隔。其中最后一个域(年)可以为空。每个域都有自己允许的值和一些特殊字符构成。使用这些特殊字符可以使我们定义的表达式更加灵活
(注意这里强制要求省去域为年的这一个部分,spring默认每年都执行)
Cron表达式参数分别表示:(从左到右)
秒(0~59) 例如0/5表示每5秒
分(0~59)
时(0~23)
日(0~31)的某天,需计算
月(0~11)
周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
特殊字符
逗号(,):指定一个值列表,例如使用在月域上1,4,5,7表示1月、4月、5月和7月
横杠(-):指定一个范围,例如在时域上3-6表示3点到6点(即3点、4点、5点、6点) 星号(*):表示这个域上包含所有合法的值。例如,在月份域上使用星号意味着每个月 都会触发
斜线(/):表示递增,例如使用在秒域上0/15表示每15秒
问号(?):只能用在日和周域上,但是不能在这两个域上同时使用。表示不指定
井号(#):只能使用在周域上,用于指定月份中的第几周的哪一天,例如6#3,意思是 某月的第三个周五 (6=星期五,3意味着月份中的第三周)
L:某域上允许的最后一个值。只能使用在日和周域上。当用在日域上,表示的是在月域 上指定的月份的最后一天。用于周域上时,表示周的最后一天,就是星期六
W:W 字符代表着工作日 (星期一到星期五),只能用在日域上,它用来指定离指定日的 最近的一个工作日