Spring 定时任务动态管理

Spring 定时任务动态管理,第1张

Spring 定时任务动态管理

pom.xml

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

<dependencys>
  <dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <version>${lombok.version}version>
  dependency>
  <dependency>
    <groupId>cn.hutoolgroupId>
    <artifactId>hutool-allartifactId>
    <version>${hutool.version}version>
  dependency>
  <dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
    <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"
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/791376.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-05
下一篇 2022-05-05

发表评论

登录后才能评论

评论列表(0条)

保存