美文网首页
SpringBoot集成schedule,实现定时任务

SpringBoot集成schedule,实现定时任务

作者: 金_鹏 | 来源:发表于2019-07-10 14:40 被阅读0次

说明:

在项目开发过程中,我们经常需要执行具有周期性的任务。通过定时任务可以很好的帮助我们实现。<br />我们拿常用的几种定时任务框架做一个比较: 2018052114225752.png2018052114225752.png

从以上表格可以看出,Spring Schedule框架功能完善,简单易用。对于中小型项目需求,Spring Schedule是完全可以胜任的。

1. springboot集成schedule

1.1 添加maven依赖

由于Spring Schedule包含在spring-boot-starter基础模块中了,所有不需要增加额外的依赖。

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

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

1.2 启动类,添加启动注解

在springboot入口或者配置类中增加@EnableScheduling注解即可启用定时任务。

package com.jetlee.schedule;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling
@SpringBootApplication
public class ScheduleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScheduleApplication.class, args);
    }

}

1.3 启动定时任务

1).Cron表达式启动定时任务

和linux下的Cron表达式时间定义规则类似,Cron表达式由6或7个空格分隔的时间字段组成


2018052114225853.png2018052114225853.png

常用的表达式有:


2018052114225854.png2018052114225854.png

下面是具体方法:

@Component
public class TaskConfig {

    @Scheduled(cron = "0/5 * * * * *")
    public void work(){
        System.out.print("执行一次\n");
    }
}

2).固定间隔任务

固定间隔任务,是从方法最后一次任务执行结束时间开始计算。并以此规则开始周期性的执行任务。

@Component
public class TaskConfig {

    @Scheduled(fixedDelay = 1000*10)
    public void work(){
        System.out.print("执行一次\n");
    }

}

3).按照指定频率执行任务,并以此规则开始周期性的执行调度。

注意 :当方法的执行时间超过任务调度频率时,调度器会在当前方法执行完成后立即执行下次任务。

@Component
public class TaskConfig {

    @Scheduled(fixedRate  = 1000*2)
    public void work(){
        System.out.print("执行一次\n");
    }
}

相关文章

网友评论

      本文标题:SpringBoot集成schedule,实现定时任务

      本文链接:https://www.haomeiwen.com/subject/uolhkctx.html