Spring Task定时任务

本文介绍了SpringTask作为定时任务的实现方式,包括XML配置和注解配置,并展示了如何使用Cron表达式进行定时设置。示例中展示了如何在Spring配置文件中配置定时任务以及在TaskJob类中使用@Scheduled注解定义任务执行周期。同时,解释了Cron表达式的各个时间元素及其含义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定时任务概述

  • 开发定时任务有三种实现方式
    • 1:JDK 自带Timer(过于简单,功能不够)
    • 2:第三方组件Quartz(过于强大,笨重)
    • 3:Spring Task (功能强大,简单易用,支持xml和注解)

定时任务实现

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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/task
        https://www.springframework.org/schema/task/spring-task.xsd">


    <context:component-scan base-package="task"/>
    <task:scheduled-tasks>
        <task:scheduled ref="taskJob" method="jojb1" cron="0/2 * * * * ?"/>
        <task:scheduled ref="taskJob" method="job2" cron="0/5 * * * * ?"/>
    </task:scheduled-tasks>



</beans>

注解配置

  • @Scheduled (在方法上)
package task.job;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class TaskJob2 {
    @Scheduled(cron = "0/2 * * * * ?")
    public void jojb1(){
        System.out.println("任务1"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

    }
    @Scheduled(cron = "0/5 * * * * ?")
    public void job2(){
        System.out.println("任务2"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

    }
}

cron表达式

cron 表达式有至少6个(或 7 个)由空格分割的时间元素,从左至右,定义:
1:秒(0-59)
2:分钟(0-59)
3:小时(0-23)
4: 月份中的日期(1-31)
5:月份(1-12 或 JAN - DEC)
6:星期中的日期(1-7 或sun - sat)
7:年份(1970-2099)
在这里插入图片描述
[注]:
在线cron 表达式通过勾选方式生成满足的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值