java taskjob_Spring Task 定时任务主要内容定时任务概述

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

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">定时任务配置

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值