Spring Task定时任务

一.概述:
1.定时任务作为一种常见的需求,在java开发定时任务主要有三种解决方案:
-JDK的timer
-第三方组件: Quartz
-Spring Task
2.Timer是jdk自带的定时任务工具,对于复杂的定时规则无法满足,在实际项目中也不常用;
Quartz功能强大,但使用相对笨重。
Spring Task 则具备两者的优点,除相关的Spring包以外,不需要额外的包,支持注解和配置文件两种形式。

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
        http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task.xsd">

<!--      设置自动化扫描范围  -->
       <context:component-scan base-package="com.vodka" />
<!--     1. XML方式 配置定时任务 -->
        <task:scheduled-tasks>
               <task:scheduled ref="taskTest" method="jobOne" cron="0/2 * * * * ?"></task:scheduled>
        </task:scheduled-tasks>
</beans>

<!--       2.注解方式:配置定时任务驱动,spring才能识别 @Scheduled 注解-->
       <task:annotation-driven></task:annotation-driven>
XML配置scheduled
@Component
public class TaskTest {
    //定义日期格式
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //定义定时任务的方法
    public void jobOne(){
        System.out.println("Happy birthday on " + simpleDateFormat.format(new Date()));
    }
}

注解配置
@Component
public class TaskTest {
    //定义日期格式
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //定义定时任务的方法
    @Scheduled(cron = "1/5 * * * * ?")
    public void jobOne(){
        System.out.println("Happy birthday on " + simpleDateFormat.format(new Date()));
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值