当前位置: 代码网 > it编程>编程语言>Java > 带你3分钟带你搞定Spring Boot中Schedule

带你3分钟带你搞定Spring Boot中Schedule

2024年07月19日 Java 我要评论
一、背景介绍在实际的业务开发过程中,我们经常会需要定时任务来帮助我们完成一些工作,例如每天早上 6 点生成销售报表、每晚 23 点清理脏数据等等。如果你当前使用的是 springboot 来开发项目,

一、背景介绍

在实际的业务开发过程中,我们经常会需要定时任务来帮助我们完成一些工作,例如每天早上 6 点生成销售报表、每晚 23 点清理脏数据等等。

如果你当前使用的是 springboot 来开发项目,那么完成这些任务会非常容易!

springboot 默认已经帮我们完成了相关定时任务组件的配置,我们只需要添加相应的注解@scheduled就可以实现任务调度!

二、方案实践

2.1、pom 包配置

pom包里面只需要引入spring boot starter包即可!

​​​​​​​
<dependencies>
    <!--spring boot核心-->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter</artifactid>
    </dependency>
    <!--spring boot 测试-->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-test</artifactid>
        <scope>test</scope>
    </dependency>
</dependencies>

​​​​​​​2.2、启动类启用定时调度

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

@springbootapplication
@enablescheduling
public class scheduleapplication {
    public static void main(string[] args) {
        springapplication.run(scheduleapplication.class, args);
    }
}

​​​​​​​2.3、创建定时任务

spring scheduler支持四种形式的任务调度!

  • fixedrate:固定速率执行,例如每5秒执行一次
  • fixeddelay:固定延迟执行,例如距离上一次调用成功后2秒执行
  • initialdelay:初始延迟任务,例如任务开启过5秒后再执行,之后以固定频率或者间隔执行
  • cron:使用 cron 表达式执行定时任务

2.3.1、固定速率执行

你可以通过使用fixedrate参数以固定时间间隔来执行任务,示例如下:

@component
public class schedulertask {
    private static final logger log = loggerfactory.getlogger(schedulertask.class);
    private static final simpledateformat dateformat = new simpledateformat("yyyy-mm-dd hh:mm:ss");
    /**
     * fixedrate:固定速率执行。每5秒执行一次。
     */
    @scheduled(fixedrate = 5000)
    public void runwithfixedrate() {
        log.info("fixed rate task,current thread : {},the time is now : {}", thread.currentthread().getname(), dateformat.format(new date()));
    }
}

运行scheduleapplication主程序,即可看到控制台输出效果:

fixed rate task,current thread : scheduled-thread-1,the time is now : 2020-12-15 11:46:00
fixed rate task,current thread : scheduled-thread-1,the time is now : 2020-12-15 11:46:10
...

​​​​​​​2.3.2、固定延迟执行

你可以通过使用fixeddelay参数来设置上一次任务调用完成与下一次任务调用开始之间的延迟时间,示例如下:

@component
public class schedulertask {
    private static final logger log = loggerfactory.getlogger(schedulertask.class);
    private static final simpledateformat dateformat = new simpledateformat("yyyy-mm-dd hh:mm:ss");
    /**
     * fixeddelay:固定延迟执行。距离上一次调用成功后2秒后再执行。
     */
    @scheduled(fixeddelay = 2000)
    public void runwithfixeddelay() {
        log.info("fixed delay task,current thread : {},the time is now : {}", thread.currentthread().getname(), dateformat.format(new date()));
    }
}

控制台输出效果:

fixed delay task,current thread : scheduled-thread-1,the time is now : 2020-12-15 11:46:00
fixed delay task,current thread : scheduled-thread-1,the time is now : 2020-12-15 11:46:02
...

​​​​​​​2.3.3、初始延迟任务

你可以通过使用initialdelay参数与fixedrate或者fixeddelay搭配使用来实现初始延迟任务调度。

@component
public class schedulertask {
    private static final logger log = loggerfactory.getlogger(schedulertask.class);
    private static final simpledateformat dateformat = new simpledateformat("yyyy-mm-dd hh:mm:ss");
    /**
     * initialdelay:初始延迟。任务的第一次执行将延迟5秒,然后将以5秒的固定间隔执行。
     */
    @scheduled(initialdelay = 5000, fixedrate = 5000)
    public void reportcurrenttimewithinitialdelay() {
        log.info("fixed rate task with initial delay,current thread : {},the time is now : {}", thread.currentthread().getname(), dateformat.format(new date()));
    }
}

控制台输出效果:

fixed rate task with initial delay,current thread : scheduled-thread-1,the time is now : 2020-12-15 11:46:05
fixed rate task with initial delay,current thread : scheduled-thread-1,the time is now : 2020-12-15 11:46:10
...

​​​​​​​2.3.4、使用 cron 表达式

spring scheduler同样支持cron表达式,如果以上简单参数都不能满足现有的需求,可以使用 cron 表达式来定时执行任务。

关于cron表达式的具体用法,可以点击参考这里: https://cron.qqe2.com/

@component
public class schedulertask {
    private static final logger log = loggerfactory.getlogger(schedulertask.class);
    private static final simpledateformat dateformat = new simpledateformat("yyyy-mm-dd hh:mm:ss");
    /**
     * cron:使用cron表达式。每6秒中执行一次
     */
    @scheduled(cron = "*/6 * * * * ?")
    public void reportcurrenttimewithcronexpression() {
        log.info("cron expression,current thread : {},the time is now : {}", thread.currentthread().getname(), dateformat.format(new date()));
    }
}

控制台输出效果:

cron expression,current thread : scheduled-thread-1,the time is now : 2020-12-15 11:46:06
cron expression,current thread : scheduled-thread-1,the time is now : 2020-12-15 11:46:12
...

​​​​​​​2.4、异步执行定时任务

在介绍异步执行定时任务之前,我们先看一个例子!

在下面的示例中,我们创建了一个每隔2秒执行一次的定时任务,在任务里面大概需要花费 3 秒钟,猜猜执行结果如何?

@component
public class asyncscheduledtask {
    private static final logger log = loggerfactory.getlogger(asyncscheduledtask.class);
    private static final simpledateformat dateformat = new simpledateformat("yyyy-mm-dd hh:mm:ss");
    @scheduled(fixedrate = 2000)
    public void runwithfixeddelay() {
        try {
            timeunit.seconds.sleep(3);
            log.info("fixed delay task, current thread : {} : the time is now {}", thread.currentthread().getname(), dateformat.format(new date()));
        } catch (interruptedexception e) {
            log.error("错误信息",e);
        }
    }
}

控制台输入结果:

fixed delay task, current thread : scheduling-1 : the time is now 2020-12-15 17:55:26
fixed delay task, current thread : scheduling-1 : the time is now 2020-12-15 17:55:31
fixed delay task, current thread : scheduling-1 : the time is now 2020-12-15 17:55:36
fixed delay task, current thread : scheduling-1 : the time is now 2020-12-15 17:55:41
...

很清晰的看到,任务调度频率变成了每隔5秒调度一次!

这是为啥呢?

current thread : scheduling-1输出结果可以很看到,任务执行都是同一个线程!默认的情况下,@scheduled任务都在 spring 创建的大小为 1 的默认线程池中执行!

更直观的结果是,任务都是串行执行!

下面,我们将其改成异步线程来执行,看看效果如何?

@component
@enableasync
public class asyncscheduledtask {
    private static final logger log = loggerfactory.getlogger(asyncscheduledtask.class);
    private static final simpledateformat dateformat = new simpledateformat("yyyy-mm-dd hh:mm:ss");
    @async
    @scheduled(fixeddelay = 2000)
    public void runwithfixeddelay() {
        try {
            timeunit.seconds.sleep(3);
            log.info("fixed delay task, current thread : {} : the time is now {}", thread.currentthread().getname(), dateformat.format(new date()));
        } catch (interruptedexception e) {
            log.error("错误信息",e);
        }
    }
}

控制台输出结果:

fixed delay task, current thread : simpleasynctaskexecutor-1 : the time is now 2020-12-15 18:55:26
fixed delay task, current thread : simpleasynctaskexecutor-2 : the time is now 2020-12-15 18:55:28
fixed delay task, current thread : simpleasynctaskexecutor-3 : the time is now 2020-12-15 18:55:30
...

任务的执行频率不受方法内的时间影响,以并行方式执行!

2.5、自定义任务线程池

虽然默认的情况下,@scheduled任务都在 spring 创建的大小为 1 的默认线程池中执行,但是我们也可以自定义线程池,只需要实现schedulingconfigurer类即可!

自定义线程池示例如下:

@configuration
public class schedulerconfig implements schedulingconfigurer {
    @override
    public void configuretasks(scheduledtaskregistrar scheduledtaskregistrar) {
        threadpooltaskscheduler threadpooltaskscheduler = new threadpooltaskscheduler();
        //线程池大小为10
        threadpooltaskscheduler.setpoolsize(10);
        //设置线程名称前缀
        threadpooltaskscheduler.setthreadnameprefix("scheduled-thread-");
        //设置线程池关闭的时候等待所有任务都完成再继续销毁其他的bean
        threadpooltaskscheduler.setwaitfortaskstocompleteonshutdown(true);
        //设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住
        threadpooltaskscheduler.setawaitterminationseconds(60);
        //这里采用了callerrunspolicy策略,当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务
        threadpooltaskscheduler.setrejectedexecutionhandler(new threadpoolexecutor.callerrunspolicy());
        threadpooltaskscheduler.initialize();
        scheduledtaskregistrar.settaskscheduler(threadpooltaskscheduler);
    }
}

我们启动服务,看看cron任务示例调度效果:

cron expression,current thread : scheduled-thread-1,the time is now : 2020-12-15 20:46:00
cron expression,current thread : scheduled-thread-2,the time is now : 2020-12-15 20:46:06
cron expression,current thread : scheduled-thread-3,the time is now : 2020-12-15 20:46:12
cron expression,current thread : scheduled-thread-4,the time is now : 2020-12-15 20:46:18
....

当前线程名称已经被改成自定义scheduled-thread的前缀!

三、小结

本文主要围绕spring scheduled应用实践进行分享,如果是单体应用,使用springboot内置的@scheduled注解可以解决大部分业务需求,上手非常容易!

项目源代码地址:spring-boot-example-scheduled

四、参考

1、https://springboot.io/t/topic/2758

到此这篇关于3分钟带你搞定spring boot中schedule 的文章就介绍到这了,更多相关spring boot中schedule 内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com