zoukankan      html  css  js  c++  java
  • SpringBoot之SpringBoot整合定时任务注解

    SpringBoot之SpringBoot整合定时任务注解

    添加MAVEN依赖:

    不需要添加,属于Spring自身的,但是不支持分布式和微服务,如果是分布式或者微服务可以采用XXL-JOB

    编写代码

      创建task包,并创建ScheduledTasks

      

     代码

    package com.springboot.demo.task;
    
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    /**
     * @author ZYGisComputer
     */
    @Component
    public class ScheduledTasks {
    
        private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
    
        /**
         * 每隔3秒执行一次
         */
        @Scheduled(fixedRate = 3000)
        public void taskService(){
            System.out.println("<执行定时任务>:"+simpleDateFormat.format(new Date()));
        }
    
    }

    在启动类中开启定时任务

    package com.springboot.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    @EnableScheduling
    @SpringBootApplication
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
    }

    启动测试:

     测试成功

    Cron表达式:

      但是这种只是非常简单的定时任务,项目中肯定不是这样的,所以这就说到了Cron表达式

      但是Cron表达式不需要自己去写,可以从网页上搜索Cron生成器,就可以了

      Cron表达式生成器

      

       只需要设置好之后拷贝到代码中就可以

      再次测试

      

       

       可以看到非常的好用

      不建议去理解cron表达式的每个符号的含义,因为我之前就理解过,一段时间就全忘了,就知道*是所有时间

    作者:彼岸舞

    时间:2021126

    内容关于:SpringBoot

    本文来源于网络,只做技术分享,一概不负任何责任

  • 相关阅读:
    数据库索引的作用和长处缺点
    ping不通的几种可能原因
    UVA
    strtok、strtok_s、strtok_r 字符串切割函数
    CheckBoxPreference组件
    EM算法原理
    Android中ExpandableListView控件基本使用
    拓扑排序的原理及事实上现
    DropdownList绑定的两种方法
    leetcode第一刷_Length of Last Word
  • 原文地址:https://www.cnblogs.com/flower-dance/p/14331562.html
Copyright © 2011-2022 走看看