Spring 定时任务动态管理

管理 Spring 中定时任务

pom.xml

<properties>
  <hutool.version>5.6.6</hutool.version>
  <lombok.version>1.18.20</lombok.version>
  <spring-boot.web.version>2.2.10.RELEASE</spring-boot.web.version>
</properties>

<dependencys>
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>${lombok.version}</version>
  </dependency>
  <dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>${hutool.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>${spring-boot.web.version}</version>
  </dependency>
</dependencys>

application.yml

server:
  port: 8081

spring:
  application:
    name: SIYUAN-SPRINGBOOT-SERVER

SYSpringBootApplication

package run.siyuan.springboot;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Field;
import java.util.Set;

/**
 * @className: SYSpringBootApplication
 * @Description: TODO
 * @author: siyuan
 * @date: 2022/4/27 2:58 PM
 */
@Slf4j
@RestController
@EnableScheduling
@SpringBootApplication
public class SYSpringBootApplication {

    @Autowired
    private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor;

    public static void main(String[] args) {
        SpringApplication.run(SYSpringBootApplication.class, args);
    }

    @Scheduled(cron = "0/5 * * * * ?")
    public void schedulingMessage1() {
        log.info("时间:{} 打印的日志,Method Name:{}", DateUtil.formatDateTime(DateUtil.date()), "schedulingMessage1");
    }

    @Scheduled(cron = "0/5 * * * * ?")
    public void schedulingMessage2() {
        log.info("时间:{} 打印的日志,Method Name:{}", DateUtil.formatDateTime(DateUtil.date()), "schedulingMessage2");
    }

    @GetMapping("/cancelTask")
    public Object cancelTask(String methodFullName) {
        Set<ScheduledTask> tasks = scheduledAnnotationBeanPostProcessor.getScheduledTasks();
        for (ScheduledTask task : tasks) {
            if (task.getTask().getRunnable().toString().equals(methodFullName)) {
                task.cancel();
            }
        }
        return "success";
    }

    @GetMapping("/updateTask")
    public String updateTask(@RequestBody JSONObject json) throws NoSuchFieldException, IllegalAccessException {
        String cron = json.getStr("cron");
        String methodFullName = json.getStr("methodFullName");
        Field registrar = scheduledAnnotationBeanPostProcessor.getClass().getDeclaredField("registrar");
        registrar.setAccessible(true);
        ScheduledTaskRegistrar taskRegistrar = (ScheduledTaskRegistrar)registrar.get(scheduledAnnotationBeanPostProcessor);
        TaskScheduler scheduler = taskRegistrar.getScheduler();
        Set<ScheduledTask> scheduledTaskSet = scheduledAnnotationBeanPostProcessor.getScheduledTasks();

        for (ScheduledTask task : scheduledTaskSet){
            if (task.getTask().getRunnable().toString().equals(methodFullName)){
                task.cancel();
                CronTask cronTask = new CronTask(task.getTask().getRunnable(), cron);

                scheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
            }
        }
        return "success";
    }

}

验证

### 取消指定定时任务
GET http://localhost:8081/cancelTask?methodFullName=run.siyuan.springboot.SYSpringBootApplication.schedulingMessage1
### 更新任务周期
GET http://localhost:8081/updateTask
Content-Type: application/json

{
  "cron": "0/10 * * * * ?",
  "methodFullName": "run.siyuan.springboot.SYSpringBootApplication.schedulingMessage2"
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值