springboot动态修改定时任务

依赖

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

配置:

printTime.cron=0/10 * * * * ?
package com.inesa.config;

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;

/**
 * 定时任务
 */
@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) {
                // 方法1
                // 使用CronTrigger触发器,可动态修改cron表达式来操作循环规则
//                CronTrigger cronTrigger = new CronTrigger(cron);
//                Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext);
//                return nextExecutionTime;



                // 方法2
                // 使用不同的触发器,为设置循环时间的关键,区别于CronTrigger触发器,该触发器可随意设置循环间隔时间,单位为毫秒
                
                PeriodicTrigger periodicTrigger = new PeriodicTrigger(timer);
                Date nextExecutionTime = periodicTrigger.nextExecutionTime(triggerContext);
                return nextExecutionTime;
            }
        });
    }
}
package com.inesa.controller;
 

import com.inesa.config.ScheduleTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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;

@Slf4j
@RestController
@RequestMapping("/test")
@Api(tags = "测试动态配置定时任务")
public class TestController {
 
    private final ScheduleTask scheduleTask;
 
    @Autowired
    public TestController(ScheduleTask scheduleTask) {
        this.scheduleTask = scheduleTask;
    }
 
    @GetMapping("/updateCron")
    @ApiOperation("动态配置定时任务-cron表达式-方法1")
    public String updateCron(@RequestParam("cron") String cron) {
        log.info("new cron :{}", cron);
        scheduleTask.setCron(cron);
        return "ok";
    }


    @GetMapping("/updateTimer")
    @ApiOperation("动态配置定时任务-时间间隔-方法2")
    public String updateTimer(@RequestParam("timer") Long timer) {
        log.info("new timer :{}", timer);
        scheduleTask.setTimer(timer);
        return "ok";
    }
}

结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,可以使用Quartz库来实现动态移除定时任务。Quartz是一个强大的调度框架,可以在后台添加、修改、移除定时任务。通过集成Quartz,可以实现在不重启应用的情况下动态移除定时任务。 可以参考中的Demo来实现动态移除定时任务的功能。在这个Demo中,后台可以添加、修改、移除定时任务,并且可以查看当前任务的状态。具体的实现可以参考Git项目地址中提供的代码。 使用Spring Boot和Quartz实现动态移除定时任务的步骤如下: 1. 首先,需要在Spring Boot项目中添加Quartz的依赖。 2. 创建一个定时任务管理类,用于管理所有的定时任务。这个类可以包含添加、修改、移除定时任务的方法。 3. 在定时任务管理类中,定义一个方法来移除定时任务。这个方法可以接受一个任务的唯一标识符作为参数,然后使用Quartz提供的API来移除该任务。 4. 在需要移除定时任务的地方,调用定时任务管理类中的移除定时任务的方法,传入要移除的任务的标识符即可。 通过以上步骤,就可以实现在Spring Boot动态移除定时任务的功能了。这样可以在不重启应用的情况下,根据需要随时移除指定的定时任务。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Springboot2-Quartz 后台可动态配置的定时任务](https://download.csdn.net/download/qq_32923745/10981179)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Spring Boot实现动态增加、删除、修改、停止定时任务](https://blog.csdn.net/qq_43813937/article/details/104183541)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [springboot不重启应用动态添加修改删除定时任务(以cron定时方式为例)](https://blog.csdn.net/qq_37549757/article/details/94393282)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值