该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
Spring Task 定时任务主要内容定时任务概述
在项目中开发定时任务应该一种比较常见的需求,在 Java 中开发定时任务主要有三种解决方案:一是使用JDK 自带的 Timer,二是使用第三方组件 Quartz,三是使用 Spring Task。
Timer 是 JDK 自带的定时任务工具,其简单易用,但是对于复杂的定时规则无法满足,在实际项目开发中也很少使用到。Quartz 功能强大,但是使用起来相对笨重。而 Spring Task 则具备前两者的优点(功能强大且简单易用),使用起来很简单,除 Spring 相关的包外不需要额外的包,而且支持注解和配置文件两种形式。
使用Spring Task实现定时任务
Spring Task 开发定时任务有两种任务配置方式:
1. XML 配置
2. 注解配置
使用 XML 配置实现定时任务创建项目,添加依赖
创建Maven项目,在pom.xml配置文件中,修改项目环境,添加spring依赖坐标
org.springframework
spring-context
5.2.4.RELEASE
添加配置文件 spring.xml
在src/main/resources目录下新建配置文件spring.xml,并设置Spring扫描器
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
定义定时任务方法新建类,添加自动注入的注解,定义定义任务的方法
package com.xxxx.task;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class TaskJob {
public void job1(){
System.out.println("任务 1:" +
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
}
public void job2(){
System.out.println("任务 2:" +
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
}
}定时任务命名空间的添加
在spring.xml配置文件中,添加定时任务的命名空间
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
修改配置文件内容如下:
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
https://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">定时任务配置