SpringBoot 动态修改定时任务频率

原文:https://cloud.tencent.com/developer/article/1627714

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;


@RestController
@RequestMapping(value = "test")
public class TestController {

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    private ScheduledFuture<?> future;

    // 线程池任务调度类
    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    private String cronStr = "0/5 * * * * *";

    @RequestMapping("/start")
    public String startCron() {
        // 创建定时计划
        future = threadPoolTaskScheduler.schedule(new MyRunnable(), new Trigger(){
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext){
                return new CronTrigger(cronStr).nextExecutionTime(triggerContext);
            }
        });
        System.out.println("DynamicTask.startCron()");
        return "startCron";
    }

    @RequestMapping("/stop")
    public String stopCron() {

        if (future != null) {
            future.cancel(true);
        }
        System.out.println("DynamicTask.stopCron()");
        return "stopCron";
    }

    @PostMapping("/change")
    public String changeCron(@RequestBody String cron) {
        cronStr = cron;
        // 先停止,在开启
        stopCron();
        future = threadPoolTaskScheduler.schedule(new MyRunnable(), new Trigger(){
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext){
                return new CronTrigger(cronStr).nextExecutionTime(triggerContext);
            }
        });
        System.out.println("DynamicTask.changeCron()");
        return "changeCron";
    }

    private class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("DynamicTask.MyRunnable.run()," + new Date());
        }
    }
}

 

调试情况如下:

1.调用start

2.调用change,并传入0/3 * * * * *

3.调用stop

 

 

posted @ 2021-05-29 18:32  这个名字想了很久~  阅读(326)  评论(0编辑  收藏  举报