Springboot定时任务 Spring task

文章目录

    • Spring Task 简单操作
      • SpringBoot注解开始
        • 1.fixDelay
        • 2.fixedRate单线程
        • 3.fixedRate多线程
        • 4.initialDelay
        • 5.cron(推荐)
        • 6.任务调度配置

Spring Task 简单操作

SpringBoot注解开始

@EnableScheduling
@SpringBootApplication
//开启spring task
@EnableScheduling
//开启多线程
@EnableAsync
public class SpringTaskApplication {
   public static void main(String[] args) {
       SpringApplication.run(SpringTaskApplication.class, args);
   }
}

1.fixDelay

程序开始运行后,在上一个任务结束时 间隔 固定时间再次执行
  @Scheduled(fixedDelay = 3000)

Springboot定时任务 Spring task_第1张图片

 @Scheduled(fixedDelay = 3000)
    //fixedDelay  上一个任务结束 等待 3s 则下一个任务开始
    public void fixedDelay(){
        log.info("这里是delayTask执行");
    }
执行结果

在这里插入图片描述

2.fixedRate单线程

fixedRate 上一个任务开始,间隔3s下一个人任务开始  
但是如果单线程操作则无法看到,需要配置为多线程
 @Scheduled(fixedRate = 10000)

Springboot定时任务 Spring task_第2张图片

    @Scheduled(fixedRate = 10000)
//    fixedRate 上一个任务开始,间隔10s下一个任务开始
//    但是如果单线程操作则无法看到,需要调节至多线程
    public void fixedRate(){
        ThreadUtil.safeSleep(11000);
        log.info("这里是fixedRateTask执行");
    }
执行结果

在这里插入图片描述

3.fixedRate多线程

多线程须在在类上加上@EnableAsync 在方法上加上@Scheduled(fixedRate = 10000)
@Async 这样才能改为多线程

Springboot定时任务 Spring task_第3张图片

    @Scheduled(fixedRate = 10000)
    @Async
//    fixedRate 上一个任务开始,间隔10s下一个任务开始
//    但是如果单线程操作则无法看到,需要调节至多线程
    public void fixedRate(){
        ThreadUtil.safeSleep(11000);
        log.info("这里是fixedRateTask执行");
    }

执行结果

在这里插入图片描述

4.initialDelay

第一次延迟多长时间后再执行 @Scheduled(initialDelay = 5000,fixedDelay = 2000)

Springboot定时任务 Spring task_第4张图片

    @Scheduled(initialDelay = 5000,fixedDelay = 2000)
//    initialDelay 第一个Task 5s后执行 其余2s
    public void initialDelay(){
        log.info("这里是initialDelayTask执行");
    }
执行结果

在这里插入图片描述

5.cron(推荐)

该参数接收一个cron表达式,cron表达式是一个字符串,字符串以5或6个空格隔开,
分开共6或7个域,每一个域代表一个含义。**corn基本可以生成所有想用的周期**
(点击下方链接即可在线生成)@Scheduled(cron = "10/3 * * * * ? ")

Springboot定时任务 Spring task_第5张图片

在线生成cron

    @Scheduled(cron = "10/3 * * * * ? ")
//    cron 第一个Task 5s后执行 其余3s
    public void cron(){
        log.info("这里是corn执行");
    }

在这里插入图片描述

6.任务调度配置

如果只是简单使用,不配置也能使用
# 任务调度线程池大小 默认 1 建议根据任务加大,工厂经理, 如果不开启异步,就是经理们亲自干活
spring.task.scheduling.pool.size=1
# 调度线程名称前缀 默认 scheduling-
spring.task.scheduling.thread-name-prefix=scheduling-
# 线程池关闭时等待所有任务完成
spring.task.scheduling.shutdown.await-termination=
# 调度线程关闭前最大等待时间,确保最后一定关闭
spring.task.scheduling.shutdown.await-termination-period=

# 任务执行线程池配置
# 是否允许核心线程超时
spring.task.execution.pool.allow-core-thread-timeout=true
#  核心线程池大小 默认 8
spring.task.execution.pool.core-size=8
# 线程空闲等待时间 默认 60s
spring.task.execution.pool.keep-alive=60s
# 线程池最大数  根据任务定制
spring.task.execution.pool.max-size=10
马上中秋节

Springboot定时任务 Spring task_第6张图片

你可能感兴趣的:(spring,spring,boot)