软件编程
位置:首页>> 软件编程>> java编程>> SpringBoot实现动态定时任务的示例代码

SpringBoot实现动态定时任务的示例代码

作者:野生java研究僧  发布时间:2022-06-22 19:27:39 

标签:SpringBoot,动态,定时,任务

前言

之前在SpringBoot项目中简单使用定时任务,不过由于要借助cron表达式且都提前定义好放在配置文件里,不能在项目运行中动态修改任务执行时间,实在不太灵活。现在我们就来实现可以动态修改cron表达式的定时任务。

配置文件

application-task.yml,其余的配置 application.yml 等就按照springBoot正常配置即可

task:
 cron: 0/10 * * * * ?
 timer: 10

定时任务核心类

import cn.hutool.core.date.DateUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.PeriodicTrigger;

import java.util.Date;

@Data
@Slf4j
@Configuration
@EnableScheduling
@ConfigurationProperties(prefix = "task")
public class WorkScheduleTask  implements SchedulingConfigurer {

private String cron;

private Long timer;

@Override

public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
       // 动态使用cron表达式设置循环间隔
       taskRegistrar.addTriggerTask(() -> {
           String dateTime = DateUtil.formatDateTime(new Date());
           String threadName = Thread.currentThread().getName();
           log.info("定时任务开始[configureTasks] :{},线程:{}", dateTime, threadName);
       }, triggerContext -> {
           // 使用CronTrigger触发器,可动态修改cron表达式来操作循环规则
           // 只能定义小于等于间隔59秒
//          CronTrigger cronTrigger = new CronTrigger(cron);
//          return cronTrigger.nextExecutionTime(triggerContext);

// 能定义大于等于间隔59秒
           // 使用不同的触发器,为设置循环时间的关键,区别于CronTrigger触发器,
           // 该触发器可随意设置循环间隔时间,单位为毫秒
           long seconds = timer * 1000;  // 毫秒转秒
           PeriodicTrigger periodicTrigger = new PeriodicTrigger(seconds);
           return periodicTrigger.nextExecutionTime(triggerContext);
       });
   }
}

提供修改cron表达式的controller

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/updateTask")
public class UpdateTaskController {

@Resource
   private WorkScheduleTask workScheduleTask;

@PostMapping("/updateCron")
   public String updateCron(String cron) {
       log.info("new cron :{}", cron);
       workScheduleTask.setCron(cron);
       return "ok";
   }

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

}

一开始定时任务的执行时机和周期都是配置文件指定的,但是我们如果对于执行的周期不满意,我们可以调用接口进行修改定时任务,但是需要注意的是,这种外暴露的接最好做一下安全校验,不是谁都可以调用,否则被别人扫描到这个接口,然后随意修改,会影响我们正常的业务流程,严重可能会造成严重损失。

来源:https://blog.csdn.net/m0_46188681/article/details/127495568

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com