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秒执行一次
  • 相关阅读:
    《全体育&#183;瑜伽》
    PowerDesigner使用教程
    Android基础之——startActivityForResult启动界面并返回数据,上传头像
    数据仓库与数据挖掘的一些基本概念
    php实现求二进制中1的个数(右移、&、int32位)(n = n & (n
    批量发短信的平台浏览总结
    php资源集
    js进阶正则表达式5几个小实例(原样匹配的字符在正则中原样输出)(取反^)
    js进阶正则表达式方括号(方括号作用)(js正则是在双正斜杠之中:/[a-z]/g)
    js进阶正则表达式修饰符(i、g、m)(var reg2=/html/gi)
  • 原文地址:https://www.cnblogs.com/fengyuduke/p/10517285.html
Copyright © 2011-2022 走看看