Spring Task定时任务

Spring Task定时任务


概述

在项目中开发中,定时任务是一种比较常见的需求,在Java中开发定时任务主要有三种解决方案:

  1. 使用JDK自带的Timer:Timer是JDK自带的定时任务工具,其简单易用,但是对于复杂的定时规则无法满足,在实际项目开发中也很少使用到。
  2. 使用第三方组件Quartz:Quartz功能强大,但是使用起来相对笨重。
  3. 使用Spring Task:而Spring Task则具备前两者的优点,功能强大且简单易用,除Spring相关的包外不需要额外的包,而且支持注解和配置文件两种形式。

通过配置文件使用Spring Task

我们先定义一个任务类MyTask,如下

@Component
public class MyTask {

    // 定时任务
    public void job(){
        System.out.println("执行任务:" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
    }
}

在配置文件中引入task的命名空间和规范,并定义定时规则,如下

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

  <!-- 扫描器 -->
  <context:component-scan base-package="org.example"/>

  <!-- 定义定时规则 -->
  <task:scheduled-tasks>
    <!--  每两秒执行一次  -->
    <task:scheduled ref="myTask" method="job" cron="0/2 * * * * ?"/>
  </task:scheduled-tasks>
</beans>

直接创建Spring的上下文环境即可,如下

public static void main(String[] args) {
    // 创建Spring的上下文环境(Spring IOC 容器),并负责实例化,配置和组装Bean
    ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
}

运行之后可以发现,每个两秒就调用一次job


通过注解使用Spring Task

通过注解使用Spring Task,我们需要先配置定时任务驱动,同样需要引入task命名空间,如下

<!-- 配置定时任务驱动。开启这个配置, spring才能识别@Scheduled注解 -->
<task:annotation-driven/>

接下来只需要在任务前加上Scheduled注解即可,如下

@Component
public class MyTask {

    // 定时任务,每两秒执行一次
    @Scheduled(cron = "0/2 * * * * ?")
    public void job(){
        System.out.println("执行任务:" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
    }
}

Cron表达式

由至少6个字段组成,也有可能是七个,字段间用空格隔开,一个字段内若由多个值可以用,,各个字段含义如下

  1. 秒(0-59)
  2. 分钟(0-59)
  3. 小时(0-23)
  4. 日期(1-31)
  5. 月份(1-12或JAN-DEC)
  6. 周几(1-7或SUN-SAT),周几的1表示周日,因为周日是一周的第一天
  7. 年份(1970-2099),年份为可选字段

常用字符如下:

  • *:可用在任意字段,表示该字段的任意时间
  • ?:只能用在日期和周几字段上,表示不明确的值,例如想在每月的20日触发调度,不管20日到底是星期几,则只能使用如下写法: 0 0 0 20 * ?, 其中最后一位只能用?,而不能使用*,如果使用*表示不管星期几都会触发。
  • -:可用在任意字段,表示一个范围,例如小时字段的0-12表示0点-12点
  • /:可用在任意字段,表示起始/增幅,例如在秒字段的5/15表示第5、20、35、50秒

其他字符可以参考https://www.cnblogs.com/javahr/p/8318728.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值