整合SpringTask实现定时任务

一、框架介绍

SpringTask是Spring自主研发的轻量级定时任务工具,相比于Quartz更加简单方便,且不需要引入其他依赖即可使用。

二、Corn表达式

  • 概述

    Cron表达式是一个字符串,包括6~7个时间元素,在SpringTask中可以用于指定任务的执行时间。

  • Cron的语法表达式

    {秒} {分} {时} {日} {月} {周}

  • Cron格式中每个时间元素的说明
    时间元素 可出现的字符 有效数值范围
    Seconds , - * / 0-59
    Minutes , - * / 0-59
    Hours , - * / 0-23
    DayofMonth , - * / ? L W 0-31
    Month , - * / 1-12
    DayofWeek , - * / ? L # 1-7或SUN-SAT
  • Cron格式中特殊字符说明
    字符 作用 示例
    列出枚举值 在Minutes域使用5,10,表示在5分和10分各触发一次
    - 表示触发范围 在Minutes域使用5-10,表示从5分到10分钟每分钟触发一次
    * 匹配任意值 在Minutes域使用*, 表示每分钟都会触发一次
    / 起始时间开始触发,每隔固定时间触发一次 在Minutes域使用5/10,表示5分时触发一次,每10分钟再触发一次
    ? 在DayofMonth和DayofWeek中,用于匹配任意值 在DayofMonth域使用?,表示每天都触发一次
    # 在DayofMonth中,确定第几个星期几 1#3表示第三个星期日
    L 表示最后 在DayofWeek中使用5L,表示在最后一个星期四触发
    W 表示有效工作日(周一到周五) 在DayofMonth使用5W,如果5日是星期六,则将在最近的工作日4日触发一次

三、整合SpringTask

  • 添加依赖

    由于SpringTask已经存在于Spring框架中,所以无需添加依赖

  • 添加SpringTask的配置

    只需要在配置类中添加一个@EnableScheduling注解即可开启SpringTask的定时任务能力。

    package top.xtslife.security.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    /**
     * 定时任务配置
     * @Author 小涛
     * @Create 2019-08-15  15:38
     */
    @Configuration
    @EnableScheduling
    public class SpringTaskConfig {
    
    }
    
  • 编写定时任务类来执行定时任务

    package top.xtslife.security.service;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    import java.util.Date;
    
    
    /**
     * @Author 小涛
     * @Create 2019-08-15  15:40
     */
    @Component
    public class SpringTaskTest {
        // 每秒打印一句话
        @Scheduled(cron="* * * * * ?")
        public void refreshSeckillGoods(){
            System.out.println("执行了秒杀商品增量更新 任务调度"+new Date());
        }
    }
    
posted @ 2019-08-15 16:38  SweetLove  阅读(614)  评论(0编辑  收藏  举报