SpringBoot实现设置动态定时任务的方法详解

 更新时间:2023年10月18日 10:22:33   作者:gblfy  
这篇文章主要介绍了SpringBoot实现设置动态定时任务的方法详解,SpringBoot是一个快速开发的Java框架,而动态定时任务是指可以在运行时动态添加、修改和删除定时任务的功能,需要的朋友可以参考下

一、第一种

1. 引入依赖

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

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

    <!-- spring boot 2.3版本后,如果需要使用校验,需手动导入validation包-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

2. 添加注解

@EnableScheduling
@SpringBootApplication
public class DemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
        System.out.println("(*^▽^*)启动成功!!!(〃'▽'〃)");
    }
}

3. application.yml

只定义了服务端口:

server: port: 8089

4. task-config.ini

定时任务执行时间配置文件:task-config.ini:

printTime.cron=0/10 * * * * ?

5. 定时任务执行类

package com.gblfy.demo.task;
 
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
 
import java.time.LocalDateTime;
import java.util.Date;
 
/**
 * 定时任务
 * @author gblfy
 */
@Data
@Slf4j
@Component
@PropertySource("classpath:/task-config.ini")
public class ScheduleTask implements SchedulingConfigurer {
 
    @Value("${printTime.cron}")
    private String cron;
 
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // 动态使用cron表达式设置循环间隔
        taskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                log.info("Current time: {}", LocalDateTime.now());
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                // 使用CronTrigger触发器,可动态修改cron表达式来操作循环规则
                CronTrigger cronTrigger = new CronTrigger(cron);
                Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext);
                return nextExecutionTime;
            }
        });
    }
}

6. 编写一个接口

使得可以通过调用接口动态修改该定时任务的执行时间:

package com.face.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author gblfy
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    private final ScheduleTask scheduleTask;

    @Autowired
    public TestController(ScheduleTask scheduleTask) {
        this.scheduleTask = scheduleTask;
    }
    //http://localhost:8089/test/updateCron?cron=0/5%20*%20*%20*%20*%20?
    @GetMapping("/updateCron")
    public String updateCron(String cron) {
        log.info("new cron :{}", cron);
        scheduleTask.setCron(cron);
        return "ok";
    }
    //http://localhost:8089/test/updateTimer?timer=5000
    @GetMapping("/updateTimer")
    public String updateTimer(Long timer) {
        log.info("new timer :{}", timer);
        scheduleTask.setTimer(timer);
        return "ok";
    }
}

启动项目,可以看到任务每10秒执行一次: 访问接口,传入请求参数cron表达式,将定时任务修改为15秒执行一次: 可以看到任务变成了15秒执行一次

http://localhost:8089/test/updateCron?cron=0/5 * * * * ?

二、第二种

除了上面的借助cron表达式的方法,还有另一种触发器,区别于CronTrigger触发器,该触发器可随意设置循环间隔时间,不像cron表达式只能定义小于等于间隔59秒。

2.1. 调整定时任务类

package com.face.controller;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 定时任务
 * @author wl
 */
@Data
@Slf4j
@Component
@PropertySource("classpath:/task-config.ini")
public class ScheduleTask implements SchedulingConfigurer {

    @Value("${printTime.cron}")
    private String cron;
    private Long timer = 10000L;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // 动态使用cron表达式设置循环间隔
        taskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                log.info("Current time: {}", LocalDateTime.now());
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                // 使用CronTrigger触发器,可动态修改cron表达式来操作循环规则
//                CronTrigger cronTrigger = new CronTrigger(cron);
//                Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext);

                // 使用不同的触发器,为设置循环时间的关键,区别于CronTrigger触发器,该触发器可随意设置循环间隔时间,单位为毫秒
                PeriodicTrigger periodicTrigger = new PeriodicTrigger(timer);
                Date nextExecutionTime = periodicTrigger.nextExecutionTime(triggerContext);
                return nextExecutionTime;`在这里插入代码片`
            }
        });
    }
}

2.2. 添加更新方法

  @GetMapping("/updateTimer")
    public String updateTimer(Long timer) {
        log.info("new timer :{}", timer);
        scheduleTask.setTimer(timer);
        return "ok";
    }

2.3. 测试

//localhost:8089/test/updateTimer?timer=5000

三、推荐方案

上面有很多弊端,弊端定时任务监控,单机故障等等,建议采用分布式任务调度框架xxl-job

到此这篇关于SpringBoot实现设置动态定时任务的方法详解的文章就介绍到这了,更多相关SpringBoot设置动态定时任务内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 通过spring注解开发,简单测试单例和多例区别

    通过spring注解开发,简单测试单例和多例区别

    这篇文章主要介绍了通过spring注解开发,简单测试单例和多例区别,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08
  • 详解如何使用java实现Open Addressing

    详解如何使用java实现Open Addressing

    这篇文章主要介绍了详解如何使用java实现Open Addressing,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • springboot swagger2注解使用的教程

    springboot swagger2注解使用的教程

    这篇文章主要介绍了springboot swagger2注解使用,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-05-05
  • SpringBoot整合Apache Ignite的实现

    SpringBoot整合Apache Ignite的实现

    本文主要介绍了SpringBoot整合Apache Ignite的实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-10-10
  • idea maven 项目src下的配置文件没有同步至target的解决操作

    idea maven 项目src下的配置文件没有同步至target的解决操作

    这篇文章主要介绍了idea maven 项目src下的配置文件没有同步至target的解决操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08
  • Java21新特性Record Patterns示例详解

    Java21新特性Record Patterns示例详解

    这篇文章主要为大家介绍了Java21新特性Record Patterns示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-09-09
  • Spring中使用AOP进行事务管理实例

    Spring中使用AOP进行事务管理实例

    这篇文章主要介绍了Spring中使用AOP进行事务管理实例,当在Spring项目中涉及数据库操作时,事务管理是非常重要的,它可以确保数据库操作的一致性和完整性,Spring提供了强大的事务管理功能,可以通过声明式或编程式两种方式进行配置,需要的朋友可以参考下
    2023-09-09
  • 通俗讲解JVM的类加载机制

    通俗讲解JVM的类加载机制

    这篇文章主要介绍了JVM的类加载机制的相关资料,帮助大家更好的理解和学习Java,感兴趣的朋友可以了解下
    2020-09-09
  • Spring Boot启动流程断点过程解析

    Spring Boot启动流程断点过程解析

    这篇文章主要介绍了Spring Boot启动流程断点过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • Java Web制作登录验证码实现代码解析

    Java Web制作登录验证码实现代码解析

    这篇文章主要介绍了Java Web制作登录验证码实现代码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09

最新评论