zoukankan      html  css  js  c++  java
  • springboot(八)-定时任务

    在我们的项目开发过程中,经常需要定时任务来帮助我们来做一些内容。

    如果我们不用springboot开发的话,我们写定时任务需要写那些配置呢?

    我们需要在application.xml文件中添加以下配置:

    1.在<beans   ..  />中添加

      xmlns:tx="http://www.springframework.org/schema/tx"

      还有xsi:schemaLocation =“...”中添加

        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task-4.3.xsd

      这就算引进task任务的功能了,接着,我们要开启task任务,配置

        <task:annotation-driven />

      然后在使用定时任务的类名上面添加注解@Component交由spring来管理,对不对。

      最后在方法名上面添加注解@Scheduled(cron="*/6 * * * * ?") 或者@Scheduled(fixedRate = 6000),这样基本就完成了。

      这样做并不算很复杂和繁琐。

    那现在用springboot开发,我们没有xml配置文件了。我们怎么做?

    springboot默认已经帮我们实现了xml文件中的一套配置,只需要添加相应的注解就可以实现。

    pom.xml

    首先在pom里面添加包含定时任务的依赖包。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

    application.java

    在启动类上面加上@EnableScheduling即可开启定时。

    @SpringBootApplication
    @EnableScheduling
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }

    创建定时任务实现类

    @Component
    public class SchedulerTask {
    
        private int count=0;
    
        @Scheduled(cron="*/6 * * * * ?")
        private void process(){
            System.out.println("this is scheduler task runing  "+(count++));
        }
    
    }

    或者

    @Component
    public class Scheduler2Task {
    
        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    
        @Scheduled(fixedRate = 6000)
        public void reportCurrentTime() {
            System.out.println("现在时间:" + dateFormat.format(new Date()));
        }
    
    }

    参数说明

    @Scheduled 参数可以接受两种定时的设置,一种是我们常用的cron="*/6 * * * * ?",一种是 fixedRate = 6000,两种都表示每隔六秒打印一下内容。

    fixedRate 说明

    • @Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行
    • @Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行
    • @Scheduled(initialDelay=1000, fixedRate=6000) :第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次
  • 相关阅读:
    linux sed
    linux vim
    linux 文本处理
    Xception: Deep Learning with Depthwise Separable Convolutions
    Residual Attention Network for Image Classification
    ResNeXt:Aggregated Residual Transformations for Deep Neural Networks
    Densely Connected Convolutional Networks
    Deep Pyramidal Residual Networks
    SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size
    Wide Residual Networks
  • 原文地址:https://www.cnblogs.com/fengyuduke/p/10517285.html
Copyright © 2011-2022 走看看