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";
    }

}

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值