Spring框架提供了对任务调度与执行的支持,本文介绍了利用Spring注解方式实现定时任务。
所需的jar包:
1、spring-beans-5.0.2.RELEASE.jar
2、spring-context-5.0.2.RELEASE.jar
3、spring-core-5.0.2.RELEASE.jar
4、spring-web-5.0.2.RELEASE.jar
5、spring-aop-5.0.2.RELEASE.jar
6、spring-expression-5.0.2.RELEASE.jar
7、spring-jcl-5.0.2.RELEASE.jar
第一步:配置web.xml
ContextLoaderListener是Spring提供的一个监听器实现类,通过该监听器,web项目在启动时会启动Spring容器。
代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>spring</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
第二步:添加applicationContext.xml配置文件
在第一步的配置方式下,web项目启动时,Spring会自动到WEB_INF下寻找applicationContext.xml文件,
读取配置,初始化bean。applicationContext.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: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.3.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.task"></context:component-scan>
</beans>
第三步:编写代码
新建com.task包,在该包下编写SpringTask类,具体代码如下:
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @author Pei
* @date 2018年2月9日
*/
@Component
public class SpringTask {
// fixedRate表示为定时循环任务,毫秒级
@Scheduled(fixedRate = 1000)
public void showDate() {
System.out.println("showDate()方法执行:" + new Date());
}
// fixedRate表示为定时循环任务,毫秒级
@Scheduled(cron = "0/5 * * * * ? ")
public void showTime() {
System.out.println("showTime()方法执行:" + new Date());
}
}
该类里面实现了两种任务执行的方式,fixedRate 是在Spring启动时就会执行,按指定的时间间隔执行,
第二种是利用cron表达式进行执行。
执行结果如下: